Weird output on converting code from C to Python -
i rum simple program check whether number prime or not in c. code looks this
void isprime(int n) { int a=0,i; for(i=1;i<=n;i++) { if(n%i==0) a++; } if(a==2) { printf("\n%d prime",n); } else { printf("\n%d not prime",n); } } int _tmain(int argc, _tchar* argv[]) { for(int i=2;i<=20;i++) { isprime(i); } return 0; }
the above code runs when compile. beginner in python , have converted same code python, looks this.
def isprime(n): a=0 x in range(1,n): if n%x==0: a=a+1 if a==2: print("{} prime".format(n)) else: print("{} not prime".format(n)) n in range(2,20): isprime(n)
but wrong output in python. output weird says
2 not prime 3 not prime 4 prime 5 not prime 6 not prime 7 not prime 8 not prime 9 prime 10 not prime 11 not prime 12 not prime 13 not prime 14 not prime 15 not prime 16 not prime 17 not prime 18 not prime 19 not prime
i have found out count of 'a' 1 less actual count required. example, in case of n=8, should 4. getting counted 3. reason?
why don't add print
statements can see code fails? adding prints should first reflex when debugging.
def isprime(n): a=0 x in range(1,n): print('x,a', x,a) if n%x==0: print('incrementing a...') a=a+1 print('a after loop:', a) if a==2: print("{} prime".format(n)) else: print("{} not prime".format(n))
output isprime(2)
:
x,a 1 0 incrementing a... after loop: 1 2 not prime
output isprime(7)
:
x,a 1 0 incrementing a... x,a 2 1 x,a 3 1 x,a 4 1 x,a 5 1 x,a 6 1 after loop: 1 7 not prime
as can see, a
never 2 because n%n
test never executed, because x in range(1,n)
, last value x
n-1
. however, if change range
range(1,n+1)
, test made:
x,a 1 0 incrementing a... x,a 2 1 x,a 3 1 x,a 4 1 x,a 5 1 x,a 6 1 x,a 7 1 incrementing a... after loop: 2 7 prime
Comments
Post a Comment