mirror of
https://bitbucket.org/Mattrixwv/projecteulerc.git
synced 2025-12-06 17:13:58 -05:00
80 lines
2.3 KiB
C
80 lines
2.3 KiB
C
//ProjectEuler/C/Problem2.c
|
|
//Matthew Ellison
|
|
// Created: 03-11-19
|
|
//Modified: 03-28-19
|
|
//The sum of the even Fibonacci numbers less than 4,000,000
|
|
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/myHelpers
|
|
//This program needs the -lm flag to compile
|
|
/*
|
|
Copyright (C) 2019 Matthew Ellison
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Lesser General Public License as published by
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
(at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Lesser General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Lesser General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
|
|
#include <stdio.h>
|
|
#include <inttypes.h>
|
|
#include "Stopwatch.h"
|
|
#include "Algorithms.h"
|
|
#include "DynamicInt64Array.h"
|
|
|
|
const uint64_t TOP_NUM = 4000000; //Holds the largest number that we are looking for
|
|
|
|
|
|
int main(){
|
|
//Create a timer for the algorithm
|
|
struct Stopwatch timer;
|
|
initStopwatch(&timer);
|
|
|
|
uint64_t fullSum = 0; //Holds the sum of all the numbers
|
|
|
|
//Start the timer
|
|
startStopwatch(&timer);
|
|
|
|
//Get all of the fibonacci numbers < TOP_NUM
|
|
struct DynamicInt64Array fibList = getAllFib(TOP_NUM - 1);
|
|
|
|
//Step through the sum of all the elements to find the even numbers and add them to the running sum
|
|
for(uint64_t cnt = 0;cnt < fibList.size;++cnt){
|
|
//Get the current number
|
|
int64_t num = getDynamicInt64Array(&fibList, cnt);
|
|
|
|
//If the number is even add it to the sum
|
|
if((num % 2) == 0){
|
|
fullSum += num;
|
|
}
|
|
//Otherwise ignore it
|
|
}
|
|
|
|
//Stop the timer
|
|
stopStopwatch(&timer);
|
|
char* timerStr = getStrStopwatch(&timer);
|
|
|
|
//Print the results
|
|
printf("The sum of the even Fibonacci numbers less than %ld is %ld\n", TOP_NUM, fullSum);
|
|
printf("It took %s to run this algorithm\n", timerStr);
|
|
|
|
//Free the memory taken by the program
|
|
destroyDynamicInt64Array(&fibList);
|
|
free(timerStr);
|
|
timerStr = NULL;
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* Results:
|
|
The sum of the even Fibonacci numbers less than 4000000 is 4613732
|
|
It took 52.000 microseconds to run this algorithm
|
|
*/
|