speed.c
· 1007 B · C
Raw
#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
// Get the limit from the first argument
if (argc != 2) {
printf("Wrong input.\n");
printf("Usage: howfast <limit>\n");
return EXIT_FAILURE;
}
long int limit = strtol(argv[1], NULL, 10);
// Setup GMP arithmetic library
mpz_t a;
mpz_t b;
mpz_t c;
mpz_init_set_ui(a, 1);
mpz_init_set_ui(b, 0);
mpz_init(c);
// Start timer
const clock_t start = clock();
// Fibonacci calculation
for (long int i = 0; i < limit; ++i) {
mpz_add(c, a, b);
mpz_set(a, b);
mpz_set(b, c);
}
// End timer
const clock_t end = clock();
// Print the result
printf("Fibonacci number %ld: ", limit);
mpz_out_str(stdout, 10, b);
printf("\n");
// Clean up
mpz_clear(a);
mpz_clear(b);
mpz_clear(c);
// Print time
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time: %f seconds\n", time_taken);
return EXIT_SUCCESS;
}
| 1 | #include <gmp.h> |
| 2 | #include <stdio.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <time.h> |
| 5 | |
| 6 | int main(int argc, char *argv[]) { |
| 7 | // Get the limit from the first argument |
| 8 | if (argc != 2) { |
| 9 | printf("Wrong input.\n"); |
| 10 | printf("Usage: howfast <limit>\n"); |
| 11 | return EXIT_FAILURE; |
| 12 | } |
| 13 | |
| 14 | long int limit = strtol(argv[1], NULL, 10); |
| 15 | |
| 16 | // Setup GMP arithmetic library |
| 17 | mpz_t a; |
| 18 | mpz_t b; |
| 19 | mpz_t c; |
| 20 | |
| 21 | mpz_init_set_ui(a, 1); |
| 22 | mpz_init_set_ui(b, 0); |
| 23 | mpz_init(c); |
| 24 | |
| 25 | // Start timer |
| 26 | const clock_t start = clock(); |
| 27 | |
| 28 | // Fibonacci calculation |
| 29 | for (long int i = 0; i < limit; ++i) { |
| 30 | mpz_add(c, a, b); |
| 31 | mpz_set(a, b); |
| 32 | mpz_set(b, c); |
| 33 | } |
| 34 | |
| 35 | // End timer |
| 36 | const clock_t end = clock(); |
| 37 | |
| 38 | // Print the result |
| 39 | printf("Fibonacci number %ld: ", limit); |
| 40 | mpz_out_str(stdout, 10, b); |
| 41 | printf("\n"); |
| 42 | |
| 43 | // Clean up |
| 44 | mpz_clear(a); |
| 45 | mpz_clear(b); |
| 46 | mpz_clear(c); |
| 47 | |
| 48 | // Print time |
| 49 | double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC; |
| 50 | printf("Time: %f seconds\n", time_taken); |
| 51 | return EXIT_SUCCESS; |
| 52 | } |