Checking for prime numbers: Any number is prime? - python

Hello dearest community,
I'm stuck on something very easy, I guess sometimes your just out of it. Anyhow, I wrote this to check for prime numbers:
num = int(input(""))
if num > 1:
for i in range(2, num-1):
if (num % i) == 0:
print(num, "is no Primenumber")
break
else:
print(i, "PRIME!!!")
(The original code doesn't print anything, but I had trouble with it, so I rewrote it for debugging purposes)
Anyway, it correctly identifies non prime numbers, but prints out this for prime numbers, lets say 7:
7
2 PRIME!!!
3 PRIME!!!
4 PRIME!!!
5 PRIME!!!

Use the below logic to find the number is prime or not. This is suited for python, as there is an else block for the for loop which gets exectued when the loop is not broken during execution which mean the number is prime.
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Not the most performance conscious, but will get the job done and is simple.
n = input("Enter a number to check if it is prime [returns True or False]: ")
n = int(n)
if n < 2:
quit()
if all(n % i for i in range(2, n)):
print(n, "PRIME!!!")

If you are concerned with performance for larger numbers it is better to use square root over number flooring division 2. Any number that is a factor greater than the square root will also have 1 that is less.
Here's a common solution:
def check_for_prime(p_in):
is_prime = True
for n in range(2, int(p_in ** 0.5) + 1):
if p_in % n == 0:
is_prime = False
break
return is_prime
num = int(input(""))
if check_for_prime(num):
print(f'{num} is prime')
else:
print(f'{num} is not prime')

Without third-party module, you can easily perform it this way:
def is_prime(number):
return all(number % n for n in range(2, number))
This way, you check:
all division between the specified number, and any number between 2 and the one before the number
the trick is to consider the fact that if any number % n gives 0, which means it is a multiple, so it can't be a prime number, and you will get a result immediately

Related

Removing multiples of a number from a list in Python

I'm new to Python and i'm working on a program which finds the prime factors of a number. My code so far looks like this:
num = int(input('\nEnter a natural number greater than 1: '))
if num <= 1:
while num <= 1:
num = int(input('\nI said greater than 1: '))
if num == 2:
print('\n', num, 'is a prime number.')
else:
toggle = 0
flist = []
for i in range(2, num - 1):
if num % i == 0:
flist.append(i)
toggle = 1
if toggle == 0:
print('\n', num, 'is a prime number.')
if toggle == 1:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
With an input of 30 for example i get this output:
Enter a natural number greater than 1: 30
30 is not a prime number.
It's prime factors are: [2, 3, 5, 6, 10, 15]
The prime factors in this case are 2, 3, 5. How can i remove their multiples ?
Thank you.
I would define an extra function to check if a number is prime
def is_prime(n):
if n>1:
for i in range(2,n):
if (n % i)==0:
return False
return True
Then I would use it inside you code to check if a number is prime before to add it to the final list of prime factors.
num = int(input('\nEnter a natural number greater than 1: '))
if num <= 1:
while num <= 1:
num = int(input('\nI said greater than 1: '))
if num == 2:
print('\n', num, 'is a prime number.')
else:
toggle = 0
flist = []
for i in range(2, num - 1):
if num % i == 0:
if is_prime(i): # append only prime numbers
flist.append(i)
toggle = 1
if toggle == 0:
print('\n', num, 'is a prime number.')
if toggle == 1:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
This gives you the right output:
Enter a natural number greater than 1: 30
30 is not a prime number.
It's prime factors are: [2, 3, 5]
You are getting the multiples of your prime factors, such as 6 = 2 × 3, 10 = 2 × 5 and 15 = 3 × 5.
To avoid those, you should divide your initial number by the prime factors as you find them, so that it won't divide again by the multiples of those prime factors.
Also, you should do that repeatedly, since numbers often have an exponent of a prime factor (for instance, 12 = 2² × 3, so you should divide by 2 twice.)
for i in range(2, num):
while num % i == 0:
flist.append(i)
num = num // i
if num == 1:
break
When you get to 1, you know you can stop.
There are also other optimizations you can do, for instance when i² is larger than num, you know num must be a prime, since you already divided it by all factors smaller than i.
You can also skip even numbers after 2, since those will never be factors.
Using the simple code above, you'll know that num is a prime whenever flist is empty. (You don't need an extra toggle to track that.) That works, since you're never dividing by num itself, so if you get to the end and haven't divided once, that means it's a prime.
For a number such as 12, your flist will have [2, 2, 3]. If you want the unique prime factors, without repetitions, you can use set(flist) to get rid of the duplicates.
Here's a solution using the Sieve of Eratosthenes to first find all primes beneath N and then go through those to find all prime factors, this should be pretty efficient
import numpy as np
def findSieve(num):
allN = np.arange(1,num+1,1)
mask = allN == allN
maskN = np.ma.MaskedArray(allN)
p = 2
while maskN[p:].count() > 0:
mask = mask & ((allN%p != 0) | (allN <= p))
maskN = np.ma.MaskedArray(maskN, mask =~ mask)
p = maskN[p:].min()
return np.asarray(maskN[maskN.mask == False])
def findPrimeFactors(num):
sieve = findSieve(num)
flist = []
num_factored = num
for i in range(1,len(sieve)) :
while num_factored % sieve[i] == 0:
flist.append(sieve[i])
num_factored = num_factored // sieve[i]
if num_factored == 1:
break
prime = len(flist) == 1
if prime:
print('\n', num, 'is a prime number.')
else:
print('\n', num, 'is not a prime number.')
print('\nIt\'s prime factors are:', flist)
num = int(input('\nEnter a natural number greater than 1: '))
findPrimeFactors(num)

How to find primes (Python)

I'm beginner in python programming and got stumpled on a Basic Question:
print the number of primes up to a given number.
For example the amount of primes before the number 100.
why my Code is not working? or what is wrong with my logic?
def count_prime(num):
newnumber = 0
for x in num:
if x%2 == 0:
newnumber = newnumber + 1
print(newnumber)
count_prime(100)
One very simple way (i.e. computationally slow) to test if a number is prime is to simply check if it can be divided by any other number.
def is_prime(n):
# If n is 0 or 1, it is not prime
if n <= 1:
return False
# Check every number between 2 and n-1
for i in range(2, n):
# If n is divisible by i, then the remainder will be zero
if n % i == 0:
return False
# Since n wasn't divisible by any other number, it must be prime
return True
To print all of the primes, you can then simply check each number.
for i in range(num):
if is_prime(i):
print(i)
This method will be very slow for large values of num. To see some much faster methods for checking the primality of a number you can have a look at this question.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")

listing prime numbers from 3 to 21 in python 3

for x in range (3,21):
if(x%2==0):
print (x,'is a not a prime number')
else:
print (x,'is a prime number')
This is my code but when it prints it says 9 is a prime number and 15 is a prime number.
Which is wrong because they aren't so how do I fix that?
.
def isPrime(N):
i = 2
while i**2 <= N:
if N % i == 0:
return False
i+=1
return True
for i in range(3, 21 + 1):
if isPrime(i):
print(i, 'is prime')
else:
print(i, 'is not a prime number')
First of all, create a function for determining whether or not a given number is prime (this is not a requirement but just a good practice). That function is not that hard: it just starts at i = 2 (starting at 1 makes no sense because every number can be divided by it) and check if N can be divided by it. If that is the case, we have found a divisor of N and thus, it isnt prime. Otherwise, continue with the next number: i += 1. The most tricky part of the loop is the stoping condition: i**2 <= N: we dont have to look further, because if some j > i is a divisor of N, then there is some other k < i that is also a divisor of N: k * j == N. If such k exists, we will find it before getting to the point where i * i == N. Thats all. After that, just iterate over each number you want to check for primality.
Btw, the best way to check for the primality of a set of number is using the Sieve of Eratosthenes
Your code only checks if a number is even. All odd numbers are not prime. So write a for-loop that checks if a odd number is divisible by any of the odd number less than that. Sometying like:
For i in (3 to n): If n mod i == 0, n is not prime.

Algorithm recommendation for calculating prime factors (Python Beginner)

SPOILER ALERT! THIS MAY INFLUENCE YOUR ANSWER TO PROJECT EULER #3
I managed to get a working piece of code but it takes forever to compute the solution because of the large number I am analyzing.
I guess brute force is not the right way...
Any help in making this code more efficient?
# What is the largest prime factor of the number 600851475143
# Set variables
number = 600851475143
primeList = []
primeFactorList = []
# Make list of prime numbers < 'number'
for x in range(2, number+1):
isPrime = True
# Don't calculate for more than the sqrt of number for efficiency
for y in range(2, int(x**0.5)+1):
if x % y == 0:
isPrime = False
break
if isPrime:
primeList.append(x)
# Iterate over primeList to check for prime factors of 'number'
for i in primeList:
if number % i == 0:
primeFactorList.append(i)
# Print largest prime factor of 'number'
print(max(primeFactorList))
I'll first just address some basic problems in the particular algorithm you attempted:
You don't need to pre-generate the primes. Generate them on the fly as you need them - and you'll also see that you were generating way more primes than you need (you only need to try the primes up to sqrt(600851475143))
# What is the largest prime factor of the number 600851475143
# Set variables
number = 600851475143
primeList = []
primeFactorList = []
def primeList():
# Make list of prime numbers < 'number'
for x in range(2, number+1):
isPrime = True
# Don't calculate for more than the sqrt of number for efficiency
for y in range(2, int(x**0.5)+1):
if x % y == 0:
isPrime = False
break
if isPrime:
yield x
# Iterate over primeList to check for prime factors of 'number'
for i in primeList():
if i > number**0.5:
break
if number % i == 0:
primeFactorList.append(i)
# Print largest prime factor of 'number'
print(max(primeFactorList))
By using a generator (see the yield?) PrimeList() could even just return prime numbers forever by changing it to:
def primeList():
x = 2
while True:
isPrime = True
# Don't calculate for more than the sqrt of number for efficiency
for y in range(2, int(x**0.5)+1):
if x % y == 0:
isPrime = False
break
if isPrime:
yield x
x += 1
Although I can't help but optimize it slightly to skip over even numbers greater than 2:
def primeList():
yield 2
x = 3
while True:
isPrime = True
# Don't calculate for more than the sqrt of number for efficiency
for y in range(2, int(x**0.5)+1):
if x % y == 0:
isPrime = False
break
if isPrime:
yield x
x += 2
If you abandon your initial idea of enumerating the primes and trying them one at a time against number, there is an alternative: Instead deal directly with number and factor it out -- i.e., doing what botengboteng suggests and breaking down the number directly.
This will be much faster because we're now checking far fewer numbers:
number = 600851475143
def factors(num):
factors = []
if num % 2 == 0:
factors.append(2)
while num % 2 == 0:
num = num // 2
for f in range(3, int(num**0.5)+1, 2):
if num % f == 0:
factors.append(f)
while num % f == 0:
num = num // f
# Don't keep going if we're dividing by potential factors
# bigger than what is left.
if f > num:
break
if num > 1:
factors.append(num)
return factors
# grab last factor for maximum.
print(factors(number)[-1])
You can use user defined function such as
def isprime(n):
if n < 2:
return False
for i in range(2,(n**0.5)+1):
if n % i == 0:
return False
return True
it will return boolean values. You can use this function for verifying prime factors.
OR
you can continuously divide the number by 2 first
n = 600851475143
while n % 2 == 0:
print(2),
n = n / 2
n has to be odd now skip 2 in for loop, then print every divisor
for i in range(3,n**0.5+1,2):
while n % i== 0:
print(i)
n = n / i
at this point, n will be equal to 1 UNLESS n is a prime. So
if n > 1:
print(n)
to print itself as the prime factor.
Have fun exploring
First calculate the sqrt of your number as you've done.
number = 600851475143
number_sqrt = (number**0.5)+1
Then in your outermost loop only search for the prime numbers with a value less than the sqrt root of your number. You will not need any prime number greater than that. (You can infer any greater based on your list).
for x in range(2, number_sqrt+1):
To infer the greatest factor just divide your number by the items in the factor list including any combinations between them and determine if the resultant is or is not a prime.
No need to recalculate your list of prime numbers. But do define a function for determining if a number is prime or not.
I hope I was clear. Good Luck. Very interesting question.
I made this code, everything is explained if you have questions feel free to comment it
def max_prime_divisor_of(n):
for p in range(2, n+1)[::-1]: #We try to find the max prime who divides it, so start descending
if n%p is not 0: #If it doesn't divide it does not matter if its prime, so skip it
continue
for i in range(3, int(p**0.5)+1, 2): #Iterate over odd numbers
if p%i is 0:
break #If is not prime, skip it
if p%2 is 0: #If its multiple of 2, skip it
break
else: #If it didn't break it, is prime and divide our number, we got it
return p #return it
continue #If it broke, means is not prime, instead is just a non-prime divisor, skip it
If you don't know: What it does in range(2, n+1)[::-1] is the same as reversed(range(2, n+1)) so it means that instead of starting with 2, it starts with n because we are searching the max prime. (Basically it reverses the list to start that way)
Edit 1: This code runs faster the more divisor it has, otherwise is incredibly slow, for general purposes use the code above
def max_prime_divisor_of(n): #Decompose by its divisor
while True:
try:
n = next(n//p for p in range(2, n) if n%p is 0) #Decompose with the first divisor that we find and repeat
except StopIteration: #If the number doesn't have a divisor different from itself and 1, means its prime
return n
If you don't know: What it does in next(n//p for p in range(2, n) if n%p is 0) is that gets the first number who is divisor of n

Python prime number calculator

prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes for online course. This program never ends, but I can't see an infinite loop in my code.
A prime number is a number that can only be divided by exclusively one and itself.
My logic is that if a number can be divided by prime numbers preceding it then it is not prime.
As the comments to your question pointed out, there is several errors in your code.
Here is a version of your code working fine.
prime = [2]
i = 3
while len(prime) <= 1000:
testlist = []
for number in prime:
testlist.append(i % number)
if 0 not in testlist:
prime.append(i)
i = i + 1
print prime
I haven't tested but you can create method like below:
def get_prime_no_upto(number):
start = 2
primes = list(range(start,number)).to_a
for no in range(start,number):
for num in range(start,no):
if ( no % num == 0) and (num != no):
primes.delete(no)
break
primes
and can use it like
print primeno(100)
cheers!
def prime_checker(number):
stop = False
prime = True
n = 2
while stop == False and n < number:
if (number) % n == 0:
prime = False
stop = True
n += 1
if prime == True:
print("It's a prime number.")
elif prime == False:
print("It's not a prime number.")
prime_checker(11)

Categories

Resources