Why does prime number checker say 9 is a prime number? - python

print "Type a number"
num = int(raw_input("> "))
if num % 2 == 0:
print "This is not a prime number"
else:
print "This is a prime number"
When I type '9' it says it's a prime number, which it isn't:
Type a number
> 9
This is a prime number
Is my code too simple? Is there something it doesn't check?

You're only checking if it is an even number, by checking if it is divisible by 2. But 9 is divisible by 3 so you need to check that also. The easiest way would be to check all numbers up to the square root of the number you're checking for primality.

All you are doing here is checking whether or not a number is evenly divisible by 2. Since 9 / 2 = 4.5, it's not evenly divisible by 2 thus going to the else clause.
Here is a condensed, working version of what you probably want:
def is_prime(a):
return all(a % i for i in xrange(2, a))

To check if number is prime you have to validate is it devisible by any number in range [2, sqrt(n)].
Following code does exactly the same:
import math
def is_prime(n):
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
This method is good for small number, but if n is real big number then you need something faster. And in this case you can use Miller–Rabin primality test which checks primality with a certain probability.

You are checking if a given number is even or not, and 9 is not even so your code prints out "This is a prime number"
Please take a look at this Stackoverflow question for a detailed explanation on how to check for prime numbers using Python.

Related

Stuck in an infinite loop with my prime number finder program

I've been working on a program for my class for a bit. It is supposed to be a prime number finder, where the def is_prime (num) function loops and continually asks the user to input more numbers, checks whether they are prime, and prints whether they are or not. If a negative number is entered, it is supposed to then quit.
def is_prime (num):
while num >= 0:
if num % 1 == num or num % num == 0:
print(num, "is a prime")
elif num % 2 == 0:
print(num, "is not a prime")
continue
elif num < 0:
print("Done. Thanks for using the program!")
break
return 0
if __name__ == "__main__":
print("This program checks if a given number is a prime number\n")
num1 = int(input("Please enter a positive number (or a negative number to exit):\n"))
is_prime(num1)
However, it only has part of that right. It reads and determines prime numbers...but instead of looping back to the function beginning it just endlessly prints the statement of whether or not it is a prime. I'm pretty sure it's a problem of where I've put my while loops, but I'm not entirely sure how to fix that.
Any help would be appreciated.
You haven't described your intended algorithm; it's not at all clear from your code. YOur first if checks whether the input number is divisible by 1 or divisible by itself ... both of which are algebraic tautologies.
Then you repeat this as long as the input remains positive. Since you never change the value of num, this is a pretty direct infinite loop.
You can't test for divisibility for each candidate factor with a different if in an if ladder.
You'll need to stash each prime you find in a list.
EG:
def sieve_primes(stop=100000):
"""Yield primes below stop."""
primes = [2]
for candidate in range(3, stop + 1, 2):
if not any(candidate % prime == 0 for prime in primes):
primes.append(candidate)
yield candidate
for prime in sieve_primes():
print(prime)
Raid it for ideas, but don't copy it verbatim. You could speed it up a lot with math.sqrt(), BTW.
HTH

How to incorporate Sieve of Eratosthenes Algorithm to find prime numbers?

For clarification, this is not the same as this question Sieve of Eratosthenes - Finding Primes Python because I don't want to generate Prime Numbers between two numbers but I want to check if a number is a prime number or not.
I made the following code to find whether a number is a prime number or not. Then I heard about the Sieve of Eratosthenes Algorithm which apparently is faster, but I don't know how to write it in the following code?
number1 = int(raw_input("""
Enter any number :- """))
if number1 == 1:
print "1 is a special case. It is neither a Prime Number nor a Normal Number. Be like 1"
if number1 == 2:
print number1, "is a Prime Number"
if number1 == 4:
print "4 is not a Prime Number"
print "2 times 2 is 4"
if number1 > 1:
for i in range(2,(number1//2)):
if number1 % i == 0:
print number1, "is not a Prime Number"
print i, "times", (number1/i), "is", number1
break
else:
print number1, "is a Prime Number"
else:
print "Please type a positive number only"
Can you guys please help me?
I did this on repl.it. I made it so every time I found a prime, I stored it in a list.
When calculating whether a number is prime, instead of going through all of the numbers leading up to it, I would go through all the numbers in the list.
This emulates what the sieve of eratasthenes would have you do.
The Sieve of Eratosthenes is a method of generating primes. It would therefore replace your code:
for i in range(2,(number1//2)):
if number1 % i == 0:
# handle non-prime
with
if number1 in previous_generated_primes:
# handle non-prime

A prime number checker that fails

It seems like a normal code and works well, but for whatever reasons when I try entering this number = 18765411123451, computer seems to freeze, any clue?
num = 18765411123451
if num > 1:
for i in range(2,num):
if num % i == 0:
print(num,"is not a prime number")
print("Because", i,"x",num//i, "=" ,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
I've tried many other numbers and the code works as it should except that number. What happened here?
it freezes because your number just too high.
The reason is for i in range(2,num): with num = 18765411123451 with is 100 trillion...
Plus the fact that python 2 will try to allocate that memory just to create the list to iterate on it (in that case use xrange)
Good news: you don't have to check until the number itself, just check until square root (included):
for i in range(2,int(num**0.5)+1):
that's more reasonable (less that 5 million iterations) and will provide the same result.
Past the square root of a number, if you haven't found divisors, you won't find any afterwards (if q is a divisor of num, then p*q == num so either p or q has to be lower or equal than square root of num

Check if the number is the prime in Python

I am learning programming from scratch first time in my life. I am learning the Python language. My first difficult task is to write algorythm which checks if the number is the prime number.
The script should work in very simple way. You enter:
is_prime(29)
and you should get output like this:
The number 29 is the prime number.
or
The number 29 is NOT the prime number.
I did not check any solution on the internet. I did it by myself. My assumptions was as follows:
from the school I remember that the prime number is divided only by 1 and by itself
'0' and '1' are not the prime number
So I wrote the code which checks if the given number is divided by all numbers from 2 to (number-1). For example if the given value is '6', the script checks first if the 6 is divided by 2. If this is true that means the number is NOT a prime number. If 6 would be not divided by 2, the script checks if 6 is divided by 3. If so, that means the number is NOT a prime number. In case of '7'number the script checks 7/2, then 7/3, then 7/4 then 7/5, then 7/6.
The code is like this:
def is_prime(number):
if number == 0 or number == 1:
print(f"The number {number} is NOT the prime number.")
elif number == 2:
print(f"The number {number} is the prime number.")
else:
for i in range(2, number):
if number % i == 0:
check = "is NOT"
break
else:
check = "is"
print(f"The number {number} {check} the prime number.")
But then, I actually realized three things:
If the number is divided by 2, definitely it is not the prime number
If the number is not divided by 2, it can be divided by 3 or by 5.
If the number is not divided by 2, is not divided by 3 and is not divided by 5 that means that this number is the prime number. The only exceptions from this rules are these three numbers 2,3 and 5.
And that's it. So I wrote the code as follows
def is_prime(number):
if number > 1:
if (number %2 == 0 and number != 2) or (number %3 == 0 and number != 3 ) or(number %5 == 0 and number != 5):
print(f"The number {number} is NOT the prime number. ")
else:
print(f"The number {number} is the prime number. ")
else:
print(f"The number {number} is NOT the prime number. ")
I think that both solutions are ok. Please correct me if I am wrong
But I would like to ask you which solution is better from the programming point of view?
Even though your first is correct and the second is not, you would gain speed in the algorithm by:
Don't try to test for divisibility if the number you are trying
to divide with is already a factor of the previous numbers, e.g.
when you have tried to divide with 2, you only need to try odd
numbers. If a number is not divisible by 2, it is clearly not
divisible by 4.
You only need to test up to the square root of
the number. At least one of the factors needs to be less than or
equal to the square root.
Your original code looks correct. The second one doesn't rule out numbers like 49.
One more thing about my first solution which you confirmed is correct.
The range to check inside the 'for' loop is:
for i in range(2, number)
But correct me if I am wrong, I think that it is enough to have range = (2, number/2)
For example let us consider the number 541 which is the prime number. My code will check modulo as follows:
541/2
541/3
541/4
.
.
.
541/538
541/539
541/540
But it is completely useless to check dividors greater than value 270 (which is almost the half of 541). If the 541 is not divided by 270 , it is obvious that it can not be divided by 271, 272, 273, 274, 275 and so on.
So I think it is enough to have:
for i in range(2, round(number/2)+1)
I had to add + 1 because otherwise I get error when I run the function for the number 3.
What do you think?
Am I right that it is enough to have range for check (2, number/2) instead of (2, number) ?
def is_prime(number):
count = 0
for i in range(1,number+1):
if number%i == 0:
count +=1
if count == 2:
print('The number {0} is the prime number.'.format(number))
else:
print('The number {0} is NOT the prime number.'.format(number))

Code for Python as Prime and function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Stuck on this problem and I couldn't find an answer and my code keeps failing.
Write a function called specialPrime which takes in an integer as an argument and returns True if the integer is a prime number and length of the integer squared is less than six digits, False if it is not a prime number or the integer squared is greater than six digits. Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
Example Interaction
Enter a number: 140
140 is not a special prime number.
Enter a number: 89
89 is a special prime number.
My code
def specialPrime(isPrime,G6):
isPrime= int(input('Enter a number:')
if isPrime < 2 return False
elif isPrime == 2
return True
for n in range(2, x)
if x % n ==0:
return False
return True
G6 = len(isPrime**2)
if G6 > 6: return False
else
return True
while True
print( isPrime + 'is a special number')
else
print( isPrime + 'is not a special prime')
`
First:
Write a function called specialPrime which takes in an integer as an argument and returns True [or] False
Your function doesn't take an integer as an argument, it takes two arguments that… I'm not sure what they're intended to be, because you ignore them anyway. So, start with that. Also, give it a meaningful name. isPrime sounds like a flag that tells you whether a number is prime, or a function that figures out whether a number is prime, not a candidate number that may or may not be prime. So:
def specialPrime(number):
The next part of your code is close, but it's got problems too:
You're supposed to be testing the value you got as an argument, not some completely different value you got from input.
if, elif, for, and all other "compound statements" in Python need colons.
if, etc., statements with multi-line bodies need those bodies indented.
What is x? You were testing isPrime, and suddenly you're testing another variable that you haven't even defined anywhere.
You return True if the number is == 2, and also if it's > 2 but has no divisors between 2 and the number. That means you aren't testing the other condition; you're just assuming it's always true.
So:
if number < 2: return False
elif isPrime == 2:
pass
for n in range(2, number):
if number % n ==0:
return False
This can all be improved in multiple ways, but those are the minimal changes to make it make sense as Python code.
Next, you're trying to take the length of a number. Numbers don't have lengths. You can take the length of a string representation of a number:
digits = len(str(number**2))
if digits > 6:
… or you can do arithmetic to test the number of digits:
square = number**2
if square > 999999:
Also, notice the names digits and square, which tell you that it's a count of digits, or a square of a number, instead of G6, which tells you that it's a group of the 6 major EU countries.
Either way, you then have some of the same problems from the first block with colons and indents again, which you need to fix the same way.
Finally:
Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
There's nothing about a while True-type loop here—it's a reasonable extension to the program, but get the basics working first.
So you need to prompt the user to type in an integer. Here is where you use input:
number = input('Enter a number:')
But the result of input is a string. If the user types 23, what you get is the string '23'. So, you need to call int to convert it:
number = int(input('Enter a number:'))
Now you have to call your function:
if specialPrime(number):
And again, you have some of the same errors with colons and indents that you need to fix.
After all of those fixes, the code will run. If there are no logic errors in your tests, it will give the right answer. If there are… well, you can debug it from there.
You could modify your code to use a couple of helper functions for each of the two requirements of special_prime(x):
def squared_less_than_six_digits(x):
return len(str(x**2)) < 6
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
return True
def special_prime(x):
return is_prime(x) and squared_less_than_six_digits(x)
def main():
user_input = 0
while True:
try:
user_input = int(input("Please enter an integer:"))
except ValueError:
print("Error: You did not enter a integer. Please try again.")
continue
else:
print("You entered the integer {}. Its square is {}.".format(user_input, user_input**2))
break
if special_prime(user_input):
print("It is a special prime.")
else:
print("It is not a special prime.")
if __name__ == "__main__":
main()
Try the above code out here!
Testing:
Prime number whose square is less than six digits:
Please enter an integer: 2
You entered the integer 2. Its square is 4.
It is a special prime.
Prime number whose square is greater than or equal to six digits:
Please enter an integer: 317
You entered the integer 317. Its square is 100489.
It is not a special prime.
Nonprime number whose square is less than six digits:
Please enter an integer: 1
You entered the integer 1. Its square is 1.
It is not a special prime.
Nonprime number whose square is greater than or equal to six digits:
Please enter an integer: 318
You entered the integer 318. Its square is 101124.
It is not a special prime.

Categories