I'm trying to write a script that divides an integer by all numbers in a range and have a value of true only if all numbers are to 0 decimal places.
Here is the code I have written so far:
n = int(input("Please enter a number (more than 0) :"))
count = 0
if n < 1 : print("Please enter a positive number")
else:
if n%2 == 0 : print("Number is not prime")
else:
for i in range(3, int(n**0.5)+1):
if i % n == 0 :
count = count + 1
count = count + 0
if count > 1 : print("Number is not prime")
else : print("Number is prime")
It prints Number is prime for any odd number.
Any ideas why this doesn't work?
Thanks.
You are wrong on two counts -
for i in range(3, int(n**0.5)+1):
if n%i == 0 : # You want to check if n is divisible by i
count = count + 1
# No need of count = count + 0 here since it does nothing
if count > 0 : print("Number is not prime") # Prime if count > 0 & not count > 1
else : print("Number is prime")
Also, you can improve the code by running the for
loop in steps of 2 rather than 1 i.e. check if n is divisible by all odd numbers from 3 to sqrt(n) instead of all numbers from 3 to sqrt(n).
for i in range(3, int(n**0.5)+1, 2): # The 3rd argument indicates steps
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments