Factorial of 100

I am trying this problem :- FCTRL2 Problem - CodeChef
According to this tutorial Tutorial for Small Factories we need to use array for this problem.
I have implemented the same using array and my code is working fine when I am giving custom input of 100, but when I run same with random inputs, it’s giving me sigsegv error. I have also tried to submit the code in codechef, but it is not accepting.
Can anyone tell me what’s wrong in this?

#include <iostream>
using namespace std;

int fact(int n) {
    int arr[160] = {1}, temp = 0, m = 1, i, k, l;
    for (i = 1; i <= n; i++) {
    	for (l = 0; l < m; l++) {
    	    // do the multiplication and store least significant bit in array
    		int x = (arr[l] * i) + temp;
    		arr[l] = x % 10;
    		temp = x / 10;
    	}
    	while (temp > 0) {
    		arr[l] = temp % 10;
    		temp /= 10;
    		l++;
    		m++;
    	}
    }
    for (int i = m - 1; i >= 0; i--) {
        cout << arr[i];   
    }
    cout << endl;
}

int main() {
	int T;
	cin >> T;
	while(T--) {
	   int n;
	   cin >> n;
	   fact(n);
	}
	return 0;
}

Pay attention to compiler warnings! :slight_smile:

[simon@simon-laptop][17:20:33]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling milanthakor-FCTRL2.cpp
+ g++ -std=c++14 milanthakor-FCTRL2.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
milanthakor-FCTRL2.cpp: In function ‘int fact(int)’:
milanthakor-FCTRL2.cpp:5:45: warning: unused variable ‘k’ [-Wunused-variable]
     int arr[160] = {1}, temp = 0, m = 1, i, k, l;
                                             ^
milanthakor-FCTRL2.cpp:24:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
+ set +x
Successful
[simon@simon-laptop][17:20:34]
[~/devel/hackerrank/otherpeoples]>echo "1
1" | ./a.out
1
milanthakor-FCTRL2.cpp:4:5: runtime error: execution reached the end of a value-returning function without returning a value
[simon@simon-laptop][17:20:42]
[~/devel/hackerrank/otherpeoples]>


1 Like

as @ssjgz mentiontioned
1> put ‘void fact’ instead of ‘int fact’
2> remove variable k as you not using it

1 Like

Check the following C++17 implementation of the Java bigInteger class for solving this problem.

https://www.codechef.com/viewsolution/43917671

@ssjgz I have changed return type of function and removed ‘k’ variable as well (It was a silly mistake, because earlier I was returning the value from function. Forgot to remove that.) But still it is giving me SIGSEGV Runtime Error. I have googled it and found out that this error caused by an invalid memory reference or a segmentation fault . But I am not able to find where I am still doing a mistake :frowning:.

Write this line out of the fact function. In other words declare all variables as global variables. It would then work perfectly.