Check if the number is the prime in Python - 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))

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

Writing a pseudocode algorithm for GCSE

My text book asks me to "write pseudo code algorithm which inputs 10 numbers. Each time a number less than zero is input, program displays which number it is, and its value. When all numbers have been input, display the average of all the negative numbers. Your algorithm should allow for the fact that there may be no negative numbers".
The issue I have is that I'm unsure on how to write pseudo code correctly, so I've written it in python code-however, that is not necessarily the task. Furthermore, I've been able to more or less to everything but the issue where I need display the average of all the negative numbers has gotten me stuck... I'm not sure how to add that into my code and I am desperate! Need this for school tomorrow!
count = 0
nums = []
while count != 10:
num = int(input ("enter a number "))
nums.append(num)
if num < 0:
print (num)
neg_nums.append(num)
count = count+1
print (neg_nums)
I actually need to print the average of all the negative numbers, however I have no clue on how I can actually code that into this...
You almost had it. Just store only the negative numbers to the list and then in the end sum all of them up and divide by the amount of negative numbers. I also changed the loop from while loop to for loop, because it makes the code clearer and more compact:
neg_nums = []
for _ in range(10):
num = int(input("enter a number "))
if num < 0:
print(num)
neg_nums.append(num)
if neg_nums:
print(sum(neg_nums) / len(neg_nums))
else:
print("no negative numbers")
We also check in the end if there were some negative numbers inputted, so we don't end up calculating 0 / 0.

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

Why do I get these numbers when I have made a range that starts from 7 to 1000000, with 7 as increment number

sevens = range(7, 1000000, 7)
x = int(input("Please enter a positive number less than one million: "))
if x in sevens:
print("{} is divisible by seven.".format(x))
My question is why do I get the following as output? Why 3510 as the starting number when the ranges begins with 7?
3510, 83517, 83524, 83531, 83538, 83545, 83552, 83559, 83566, 83573, 83580, 83587, 83594, 83601, 83608, 83615, 83622, 83629, 83636, 83643......
Does the error has to do something with the computer memory or is the problem in my IDE(Pycharm Jetbrains)?
Thank you!
To test if a number is fully divisible by another number use the % (aka Modulo) operation that gives you the rest of said division:
x = int(input("Please enter a positive number less than one million: "))
if x%7 == 0:
print("{} is divisible by seven.".format(x))
print("It fits {} times.".format(x//7))
else:
print("{} is not divisible by seven - theres a rest of {}.".format(x,x%7))
Further reading:
Modulo operator in Python
binary-arithmetic-operations - binary = operating on 2 things, % is inside that.
This is your IDE (Pycharm) problem. Update your IDE. I ran the same code and I have the output starting from 7,14,... and so on.

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

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.

Categories