-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewGMPFibonacci.c
More file actions
117 lines (89 loc) · 2.82 KB
/
newGMPFibonacci.c
File metadata and controls
117 lines (89 loc) · 2.82 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
//The fibonacci function using a new recursive algorithm
/* The formulae used to calculate the fibonacci number are:
fib(2n+1) = fib((n/2))*fib((n/2)-1) + fib((n/2))*fib((n/2)+1)
fib(2n) = fib(n/2) * fib(n/2) + fib((n/2) - 1) * fib((n/2) - 1)
*/
void fibonacci(unsigned int n, mpz_t r){
//The base cases
if(n == 0){
mpz_set_ui(r, 0);
}
else if(n == 1){
mpz_set_ui(r, 1);
}
else{
unsigned int k = n/2;
//For even number th fibonacci number
if(n%2 == 0){
//Temporary variables for calculations
mpz_t fk1, fk2, mulTem1, mulTem2;
mpz_inits(fk1, fk2, mulTem1, mulTem2, NULL);
fibonacci(k, fk1);
fibonacci(k-1, fk2);
mpz_mul(mulTem1, fk1, fk1);
mpz_mul(mulTem2, fk2, fk2);
mpz_add(r, mulTem1, mulTem2);
//Freeing the allocated memory
mpz_clears(fk1, fk2, mulTem1, mulTem2, NULL);
}
//For odd number th fibonacci number
else{
//Temporary variables for calculations
mpz_t fk1, fk2, fk3, mulTem1, mulTem2;
mpz_inits(fk1, fk2, fk3, mulTem1, mulTem2, NULL);
fibonacci(k, fk1);
fibonacci(k-1, fk2);
fibonacci(k+1, fk3);
mpz_mul(mulTem1, fk1, fk3);
mpz_mul(mulTem2, fk1, fk2);
mpz_add(r, mulTem1, mulTem2);
//Temporary variables for calculations
mpz_clears(fk1, fk2, fk3, mulTem1, mulTem2, NULL);
}
}
}
int main(int argc, char* argv[]){
//Checking for command-line arguments
if(argc < 2){
printf("Use: %s <output_filename>\n", argv[0]);
return 1;
}
unsigned int n = 0;
mpz_t r;
mpz_init(r);
//Taking input and handling errors
do{
printf("\nInput a whole number: ");
scanf("%u", &n);
if (n < 0){
printf("\nInvalid input! Please enter a whole number.\n");
}
} while (n < 0);
//Calling the fibonacci function
fibonacci(n, r);
//Taking the output in a file
FILE *fp = fopen(argv[1], "w");
//Checking if the file opened
if(!fp){
printf("\nFailed to open the file.");
//Freeing the allocated memory
mpz_clear(r);
return 1;
}
else{
printf("\nOpened the file, sucessfully.\n");
}
fprintf(fp, "fib(%u) = ", n);
mpz_out_str(fp, 10, r);
fprintf(fp, "\n");
//Closing the file
fclose(fp);
//Printing the results
printf("\nCopied the fibonacci result to the file.\n");
//Freeing the allocated memory
mpz_clear(r);
return 0;
}