Home > Enterprise >  A problem was caused by an array that was not initialized
A problem was caused by an array that was not initialized

Time:05-01

I am trying to solve a execise, which amis to find the Last Digit of a Large Fibonacci Number, and I try to search for others' solution, and I find one here: https://www.geeksforgeeks.org/program-find-last-digit-nth-fibonnaci-number/, then I copy and paste the method 2, and I just changed the ll f[60] = {0}; to ll f[60]; but this doesn't work properly on CLion, my test code int n; std:cin>>n; `

for (int i = 0; i < n; i  ) {
    std::cout << findLastDigit(i) << '\n';
}

return 0;

}` the error: SIGSEGV (Segmentation fault). Could someone give me a hint or reference or something?

CodePudding user response:

For a large number, you probably want to utilize a cache. Could you do something like this?

// Recursive solution
int fib(int n, int cache[]) {
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    if (cache[n]!= 0) {
        return cache[n];
    }
    cache[n] = fib(n - 1, cache)   fib(n - 2, cache);
    return cache[n];
}

// Iterative solution
int fib(int n) {
    int cache[n   1];
    cache[0] = 0;
    cache[1] = 1;
    for (int i = 2; i <= n; i  ) {
        cache[i] = cache[i - 1]   cache[i - 2];
    }
    return cache[n];
}

CodePudding user response:

I modified the code as described:

// Optimized Program to find last
// digit of nth Fibonacci number
#include<bits/stdc  .h>
using namespace std;

typedef long long int ll;

// Finds nth fibonacci number
ll fib(ll f[], ll n)
{
    // 0th and 1st number of
    // the series are 0 and 1
    f[0] = 0;
    f[1] = 1;

    // Add the previous 2 numbers
    // in the series and store
    // last digit of result
    for (ll i = 2; i <= n; i  )
        f[i] = (f[i - 1]   f[i - 2]) % 10;

    return f[n];
}

// Returns last digit of n'th Fibonacci Number
int findLastDigit(int n)
{
    ll f[60]; // = {0};

    // Precomputing units digit of
    // first 60 Fibonacci numbers
    fib(f, 60);

    return f[n % 60];
}

// Driver code
int main ()
{
    ll n = 1;
    cout << findLastDigit(n) << endl;
    n = 61;
    cout << findLastDigit(n) << endl;
    n = 7;
    cout << findLastDigit(n) << endl;
    n = 67;
    cout << findLastDigit(n) << endl;
    return 0;
}

and run it flawlessly in online c compiler environment:

1
1
3
3

This indicates that your program has additional changes.

Segfaults are caused when trying to read or write an illegal memory location. This indicates that your code might take an uninitialized value out of f and uses it in an inappropriate way to access memory.

  • Related