lundi 19 février 2018

Displaying the modulo of a Large Fibonacci number with another (large) number

While writing the code for displaying the modulo of a large fibonacci number with another number, I have this problem while submitting. It does not accept the submission because my program timed out. Please go through the code

#include <iostream>

unsigned long long get_fibonacci_huge(unsigned long long n, unsigned long long m) {
    if (n <= 1)
        return n;

    unsigned long long previous = 0;
    unsigned long long current  = 1;
    for (long long i = 0; i < n - 1; ++i) {
        unsigned long long tmp_previous = previous%m;
        previous = current%m;
        current = (tmp_previous + current)%m;
    }

    return current;
}

int main() {
    unsigned long long n, m;
    std::cin >> n >> m;
    std::cout << get_fibonacci_huge(n, m) << '\n';
}

While following this algorithm, it times out. I just want to know if there is a better way of doing this. just for your reference, one of the test case was

n = 99999999999999999 and m = 2

Thank you.

Aucun commentaire:

Enregistrer un commentaire