'What is the problem in my code why it can't return long long int value from a function in c [closed]
#include<stdio.h>
int facsum(long long int f)
{
long long int sum=1,i;
if(f>0)
{
for(i=1;i<=f;i++)
{
sum*=i;
}
}
return sum;
}
int main()
{
long long int M,N;
while(scanf("%lld %lld",&M,&N)!=EOF)
{
long long int sum=facsum(M)+facsum(N);
printf("%lld\n",sum);
}
return 0;
}
This code is for https://www.beecrowd.com.br/judge/en/problems/view/1161 this problem but i don't know why my code is not returning long long int value.
Solution 1:[1]
You declared the function as returning int. If you want the return value to be long long int declare it as such:
long long int facsum(long long int f) // return type changed HERE
{
long long int sum=1;
long long int i;
if(f>0)
{
for(i=1;i<=f;i++)
{
sum*=i;
}
}
return sum;
}
It is very strange that you used sum in your function when it only does multiplication. This makes it difficult for people to understand your code.
Also, be aware that a long long int typically is 64 bits, and the maximum value that will fit in that is about 10^19. 20! is greater than this. So any value of f passed to the function greater than 19 will return an incorrect answer.
Solution 2:[2]
Sir, inside the while loop you are declaring a new variable each time:
long long int sum=facsum(M)+facsum(N); // must remove long long int
As another user mentioned the return type is also an issue, but the main problem is sum declaration repeatedly in the while loop
Down below is a working version, please note I used another notation to get printf working properly with long long int, I used %I64d, that because I am in a windows based system.
#include<stdio.h>
long long int facsum(long long int f)
{
long long int sum=1,i;
if(f>0)
{
for(i=1;i<=f;i++)
{
sum*=i;
}
}
return sum;
}
int main()
{
long long int M,N, sum = 0;
while(scanf("%lld %lld",&M,&N) == 2) // if get warring or error try %I64d instead %lld
{
sum=facsum(M)+facsum(N); // remove long long int
printf("%lld\n",sum);
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
