Reputation: 1
while running this code I am getting floating point exception pls explain why it is coming so.
#include <stdio.h>
int gcd(long int, int);
int main() {
int t, n, a, i;
long int abc;
scanf("%d", &t);
while (t--) {
abc = 1;
scanf("%d", &n);
abc = n * (n - 1);
for (i = n - 2; i > 1; i--) {
a = gcd(abc, i);
abc = ((abc * i) / a);
}
printf("%ld \n", abc);
}
return 0;
}
int gcd(long int a, int b) {
if (b == 0)
return a;
else {
return (b, a % b);
}
}
Upvotes: 0
Views: 336
Reputation: 386
You should change a few things:
1) if(a == 0)
instead of b==0
and return
variable b
2) Use recursion gcd(b%a, a)
if (a == 0)
return b;
else {
return gcd(b%a, a);
}
And you can also use this short version
return a ? gcd(b%a,a) : b;
Proof:
We have m = n * (m div n) + m Mod n
.
This equation is correct even if n = 1
, because m div 1 = m
and m mod 1 =0
.
If n
and m
mod n it's multiple of d
, also m
is multiple of d
, because n * (m div n)
and m mod n / d
.
On the other hand if m
and n
is multiple of e
, to because m mod n = m -n * (m div n)
is also multiple of e
.
Upvotes: 0
Reputation: 1352
The else part in gcd
function is bogus. You probably wanted to call gcd
recursively and instead you are returning a % b
. And as a result if a % b == 0
you divide by 0 on line 13.
The expression (b, a % b)
is evaluated as two subexpressions separated by comma operator. The value of b is forgotten and the value of the whole expression becomes a % b
.
The correct version:
int gcd(long int a, int b) {
if (b == 0)
return a;
else {
return gcd(b, a % b);
}
}
Upvotes: 4