Home > Software design >  Hackerrank Solution in a different way. Receiving segmentation fault for test case 2 and 3
Hackerrank Solution in a different way. Receiving segmentation fault for test case 2 and 3

Time:08-11

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int t; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0  ){
        long long int n, sum =0, *fib; 
        scanf("%lld",&n);
        fib = (long long int*) malloc(n * sizeof(long long int));
        fib[0] = 0;
        fib[1] = 1;
        
        for(long long int i = 2; i < n; i  )
        {
           fib[i] = fib[i-1]   fib[i-2];
                if((fib[i] <= n) && (fib[i] % 2 == 0))
                {
                    sum  = fib[i];
                }
                if(fib[i] >= n)
                {
                    i = n;
                } 
            
        }
        printf("%lld\n", sum);
        free(fib);
    }
    return 0;
}

The question is to print the sum of even fibonacci number till the number n. The constraints are 1< test cases < 10^5 and 1<= Number <= 10^16 I know there is a different way of solving this problem by using only sum of even Fibonacci formula but what I want to know is why is it giving me segmentation fault even after using long long int. I tried even unsigned types still it doesn't work. Any idea where it is going wrong? I read all the other answers on this question its not helping.

CodePudding user response:

int main(){
    int t; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0  ){
        long long int n, sum =0, fib[100]; 
        scanf("%lld",&n);
        fib[0] = 0;
        fib[1] = 1;
        
        for(long long int i = 2; i < 100; i  )
        {
           fib[i] = fib[i-1]   fib[i-2];
                if((fib[i] <= n) && (fib[i] % 2 == 0))
                {
                    sum  = fib[i];
                }
                if(fib[i] >= n)
                {
                    i = n;
                } 
            
        }
        printf("%lld\n", sum);
        
    }
    return 0;
}

after allocating the memory statically instead of dynamically the code worked. thanks everyone for the suggestions!

CodePudding user response:

Here's a solution (with my OLD 32 bit compiler...)

Why do you make it hard on yourself?

int main( void ) {
    long f[2] = { 0, 1 };
    long sum = 0;
    long sumtwo = 0;

    for( int i = 2; i < 15; i   ) {
        int evenodd = i & 0x1;
        if( evenodd == 0 )
            sum  = f[ 0 ]   f[ 1 ];

        sumtwo = f[ 0 ]   f[ 1 ];
        printf( "%dth - %ld  %ld  %ld\n", i, f[0], f[1], sumtwo );

        f[ evenodd ] = sumtwo;
    }
    printf( "Final sum of evens - %ld\n", sum );

    return 0;
}
  • Related