C Implementation of Problem 25

View source code here on GitHub!

Includes

Solution

uint64_t p0025()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program. It is not present when compiling for the Unity test runner.

 1/*
 2Project Euler Problem 25
 3
 4Problem:
 5
 6The Fibonacci sequence is defined by the recurrence relation:
 7
 8    Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
 9
10Hence the first 12 terms will be:
11
12    F1 = 1
13    F2 = 1
14    F3 = 2
15    F4 = 3
16    F5 = 5
17    F6 = 8
18    F7 = 13
19    F8 = 21
20    F9 = 34
21    F10 = 55
22    F11 = 89
23    F12 = 144
24
25The 12th term, F12, is the first term to contain three digits.
26
27What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
28*/
29#ifndef EULER_P0025
30#define EULER_P0025
31#include <stdint.h>
32#include <inttypes.h>
33#include <stdio.h>
34#include "include/macros.h"
35#include "include/bcd.h"
36
37uint64_t EMSCRIPTEN_KEEPALIVE p0025() {
38    uint64_t answer = 2;
39    BCD_int a = BCD_one, b = BCD_one;
40    do {
41        iadd_bcd(&a, b);
42        swap(a, b);
43        answer++;
44    } while (b.decimal_digits < 1000);
45    free_BCD_int(a);
46    free_BCD_int(b);
47    return answer;
48}
49
50PROGRAM_TAIL("%" PRIu64, p0025)
51#endif

Tags: fibonacci-number, large-numbers