0

I am creating a script that calculates the sum of first n Fibonacci numbers and returns the last digit of the sum. The python script works perfect but the C++ script does not and the logic is same.

Any help will be appreciated.

Python Code

def calc_fib(n):

    f = [0, 1]
    for i in range(2, 61):
        f.insert(i, (f[i-1] + f[i-2]) % 10)
    rem = n % 60
    quotient =  (n - rem) / 60
    return int((sum(f) * quotient + sum(f[0: rem+1])) % 10)

n = int(input())
print(calc_fib(n))

C++ Code

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

long long fibonacci_sum_last_digit(long long n) {
    vector<int> f(n + 1);
    f[0] = 0;
    f[1] = 1;
    for (int i = 2; i <= 60; i++){
        f[i] = (f[i-1] + f[i-2]) % 10;
    }
    int rem = n % 60;
    int quotient = (n - rem) / 60;
    return (accumulate(f.begin(), f.end(), 0) * quotient + accumulate(f.begin(), f.begin() + rem + 1, 0)) % 10;
}

int main() {
    int n;
    cin >> n;
    if (n <= 1)
        cout << n;
    else
        cout << fibonacci_sum_last_digit(n) << '\n';
    return 0;
}

2
  • 1
    Tip: using namespace std; is a bad habit to get into and if you can stop now you might avoid a whole lot of headaches in the future. The std:: prefix is there for a reason: It avoids conflict with your own classes, structures and variables especially when you’re importing a lot of header files which may define a lot more things than they superficially appear to. Commented Sep 16, 2020 at 7:15
  • 1
    Is this supposed to return the last digit of the sum, or the sum of the last digits? Commented Sep 16, 2020 at 7:17

1 Answer 1

4
vector<int> f(n + 1);
f[0] = 0;
f[1] = 1;
for (int i = 2; i <= 60; i++){
    f[i] = (f[i-1] + f[i-2]) % 10;
}

The vector is size n+1 and you access until 60 => it's a bug

This should fix :

vector<int> f(60 + 1);

Or

vector<int> f; 
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= 60; i++){
    f.push_back((f[i-1] + f[i-2]) % 10);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The second approach is nice because it's impossible to mis-size the vector. It always has the right size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.