0

Please help me explain how this works

I found it as someone's comment. It's a program for checking if the input number is a prime. n=0 i=2 x=int(input("input a number: ")) while i<=x: if (x%i == 0): n+=1 i+=1 if n==1: print("It is a prime number.") else: print("It is not a prime number.")

10th Mar 2019, 9:05 AM
Tumbu Nkeng John
Tumbu Nkeng John - avatar
2 Answers
+ 2
Your code checks all integers from 2 up to and including x to see if each number exactly divides x. If it only finds one such number (i.e. x itself) it confirms that x is prime.
10th Mar 2019, 9:10 AM
Russ
Russ - avatar
+ 2
It takes an input x then runs a loop from 2 to x. It then checks if the remainder of x/i is zero incrementing n(found non-prime) then increments i to move onto the next factor... It would be better like this: num=int(input("Enter a number")) count=0 for i in range(2,num): if num%i==0: count+=1 if count>0: print('not prime') else: print('Prime')
10th Mar 2019, 9:45 AM
Mensch
Mensch - avatar