0

While the program works as expected on low numbers there is no output when input is big

I tried changing data types to longest there is (unsigned long long) which is more than required yet nothing changed. Changed from cin to scanf just to try but nothing. There is no output no error nothing I tried v it is supposed to give the remainder when nth fibonacci number is divided by changing int i to long long as well but no the said input is 9999999999999 2

#include <iostream>
#include <array>

using namespace std;

int main()
{
    int m;
    long long n;
    scanf("%lli,%i", &n , &m);
    int numbers[n];
    numbers[0] = 0;
    numbers[1] = 1;
    for (int i = 2; i <= n; i++) 
    {
        numbers[i] = numbers[i - 1] + numbers[i - 2];
        if (numbers[i] >= m)
            numbers[i] %= m;
    }
    
    cout << numbers[n];
    
    return 0;
}
  • 4
    `int numbers[n];` is illegal in C++ without compiler extensions since the value of `n` must be known at compile time, not at runtime. Instead prefer `std::vector numbers(n);` if you need a runtime sized container. – Cory Kramer Nov 16 '22 at 16:35
  • Usual issue, see it all the time. `int numbers[n];` is not legal C++, and (unrelated) crashes when `n` is large. Usual solution, use a `std::vector`. – john Nov 16 '22 at 16:37
  • 1
    Why are you even using an array? – Blindy Nov 16 '22 at 16:37
  • Even if `n` is of a type large enough to hold your input, is `int` large enough to hold all the intermediate values you're computing? Hint: You might need to perform arithmetic modulo `m` the entire time, not just at your final step. The 9,999,999,999th Fibonacci number is way too large to fit in an `int`. – Nathan Pierson Nov 16 '22 at 16:37
  • Also why are you even creating an array of all `n` many numbers? All you care about is the value of the final number modulo `m`. – Nathan Pierson Nov 16 '22 at 16:38
  • 2
    You'll need a better algorithm too. Counting up one-by-one all the way to 9999999999999 would take a while. – harold Nov 16 '22 at 16:46
  • [Computing the nth Fibonacci number](https://stackoverflow.com/questions/66541088/computing-the-1-millionth-fibonacci-number/66541479#66541479). – PaulMcKenzie Nov 16 '22 at 17:26

0 Answers0