-
Notifications
You must be signed in to change notification settings - Fork 5
/
fibonacci_series.c
89 lines (70 loc) · 1.35 KB
/
fibonacci_series.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Fibonacci series and even Fibonacci numbers.
* https://projecteuler.net/problem=2
*/
#include <stdio.h>
#define LIMIT 4000000
/**
* Print fibonacci series less than LIMIT.
*
* @param int a
* @param int b
*
* @return void
*/
void print_fibonacci_series(int a, int b)
{
int sum = a + b;
if (sum > LIMIT) {
return;
}
printf("%d ", sum);
print_fibonacci_series(b, sum);
}
/**
* Print N fibonacci series.
*
* @param int n
*
* @return unsigned long
*/
unsigned long num_fibonacci(int n)
{
if (n < 2) {
return (unsigned long) n;
}
return num_fibonacci(n - 1) + num_fibonacci(n - 2);
}
/**
* Get sum of even fibonacci series up to LIMIT.
*
* @param int a
* @param int b
* @param int c
*
* @return unsigned long
*/
unsigned long sum_even_fibonacci(int a, int b, int c)
{
static unsigned long sum = 0;
if (c > LIMIT) {
return 0;
}
sum += c;
a = b + c;
b = c + a;
sum_even_fibonacci(a, b, a + b);
return sum;
}
int main()
{
int limit;
print_fibonacci_series(-1, 1);
printf("\n\nSum of even fibonacci up to %d is %lu", LIMIT, sum_even_fibonacci(1, 1, 2));
printf("\n\nEnter N to print N fibonacci numbers: ");
scanf("%d", &limit);
for (int i = 0; i < limit; i++) {
printf("%lu ", num_fibonacci(i));
}
return 0;
}