user2975192
user2975192

Reputation: 327

Dividing integer by all numbers in a range in Python

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.

Upvotes: 1

Views: 12465

Answers (3)

albert behar
albert behar

Reputation: 1

inp = int(input("Type a number: "))  

isprime = 'true'                

for x in range(2, inp):
    y = (inp % x)
    if y == 0:
        isprime = 'false'

print(isprime)

Upvotes: 0

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

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

Upvotes: 0

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

if count > 1 : print("Number is not prime") should be if count >= 1 : print("Number is not prime"). Also, in if n%2 == 0 : print("Number is not prime"), count should be incremented. Better, why even have if n%2 == 0 : print("Number is not prime")? Change 3 in for i in range(3, int(n**0.5)+1): to 2, and that if statement can be removed.

PS: count = count + 0 does nothing, so remove it.

Upvotes: 1

Related Questions