I wanted to check if a fraction 2 4 (for example) can be simplified to 1 2!!
However logical condition fails.
#include <stdio.h>
int main()
{
int a,b,live=1;
printf("\n\nInput integers for fraction:");
scanf(" %d%d",&a,&b);
while(live){
if(!(a%2 && b%2)){
a/=2;
b/=2;
}else if(!(a%3 && b%3)){
a/=3;
b/=3;
}else if(!(a%5 && b%5)){
a/=5;
b/=5;
}else if(!(a%7 && b%7)){
a/=7;
b/=7;
}else live--;
}
printf("Simplified Fraction is %d/%d",a,b);
}
The condition a%2
is equivalent to a%2 != 0
, i.e. it tests if a
is not divisible by 2. From De Morgan's Laws, the condition if(!(a%2 && b%2))
is equivalent to if(!(a%2) || !(b%2))
or if((a%2 == 0) || (b%2 == 0))
, which is not what you want.
You really want to test if((a%2 == 0) && (b%2 == 0))
-- that is, if both are divisible by 2, not if either is divisible by 2. Writing it this way is also much less confusing.
And it should also be obvious that in order to simplify any fraction, you need to test for all possible prime factors, which is impossible to do with a finite number of if
statements. The recommended way of doing this is to use the Euclidean algorithm to determined the greatest common divisor of the numerator and denominator, and then you divide both by the GCD to get the fraction in reduced form.