Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c++ - Fibonacci, but with different starting numbers. Code works in most cases, but not all

So I have an exercise of finding a Fibonacci sequence but with different starting number and I can't figure out why my code works most of the time, but not in some cases.

My code is based on a formula (link: https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/)

If n is even then k = n/2:
F(n) = [2*F(k-1) + F(k)]*F(k)

If n is odd then k = (n + 1)/2
F(n) = F(k)*F(k) + F(k-1)*F(k-1)

-

#include <map>
#include <iostream>
#include <cmath>
using namespace std;

#define long long long
map<long, long> F;

long f(long n, long M) {
    if (F.count(n)) return F[n];
    long k = n / 2;
    if (n % 2 == 0) { // n=2*k
        return F[n] = (f(k, M)*f(k, M) + f(k - 1, M)*f(k - 1, M)) % M;
    }
    else { // n=2*k+1
        return F[n] = (f(k, M)*f(k + 1, M) + f(k - 1, M)*f(k, M)) % M;
    }
}

int main() {
        long a, b, M, n;
        cin >> a >> b >> n >> M;
        M = pow(10, M); //modulo
        F[0] = b;
        F[1] = a + b;
        //base cases
        for (int i = 2; i < 100; i++) F[i] = (F[i - 1] + F[i - 2]) % M;


        if (n != 0) cout << f(n - 1, M) << endl;
        else cout << a<<endl;

        F.clear();


}

a - is the first number of the sequence. b - the second. n - which number of the sequence i want to find. m - modulo.

I don't understand why it works with cases like

98 25 1000000000 1              //answer is 3

but it doesn't work with

34 88 224242 2     //my answer is 12, correct is 92

code works fine with regular Fibonacci starting numbers (0 and 1)

I would be really grateful for your help.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...