Counting divisors to detect prime number in python 3.7.4 - python

I tried to write a code to detect prime numbers myself and accidentally, I found this which is working just fine:
def prime_number_check(inp):
setp = [ ]
res = [ ]
count = 0
for x in range(1, inp):
setp.append(x)
print(setp) #just to control the set
for y in setp: #set of dividers
if inp % setp[y-1] == 0:
res.append(setp[y-1])
else:
continue
print(res) #just to control the set
for z in res:
count += 1
if count > 1:
print(inp, "is not a prime number!")
else:
print(inp, "is a prime number!")
I tried to divide the input number, which will be checked whether it is prime or not, to the numbers smaller than itself and wanted to detect the result set whether it has float results or int results, then remove float results with res.remove(), then if there is int result other than 1, print not a prime, otherwise print prime, but I failed; instead found this code which counts divisors.
Could you help me to find out how can I make float/int check in a list and return a result? I tried bool(), and isinstance() but always got an error about iterability.

def prime(*arg):
if num<2:
return 0
else:
t=0
for x in range(2,num+1):
k=0
for y in range(1,x+1):
if x%y == 0:
k += 1
if k == 2:
t += 1
return t
Here I actually not considered 0 and 1 as prime . I hope you got my simple code in python.

Related

How to manage huge divisions – integer division result too large for a float

I've been trying to make a python script that tells if a number is a prime number or not. I've tried by my own way, but I ran into a big problem.
When I'm trying to divide a big number it gives me a error OverflowError: integer division result too large for a float. I found that if I use // method at the divide it stops giving me that error, but I can't find a way to find if the number is prime.
This is the first script I made, that gave the OverflowError: integer division result too large for a float:
product = 1
list = []
i = 13
for num in range(i):
list.append(num)
list = [x for x in list if x != 0]
for x in list:
product *= x
final = product + 1
final2 = final/i
if float.is_integer(final2) == True:
print("Prime")
else:
print("Not prime")
As you can see, I used to divide the final by i. If the number was a prime one, it will return float.is_integer. But if the i variable was a big number, it will give the error.
Then I used the // method but I have no idea how to check if the the number is prime.
Here is the second scrpt, it's the same but replacin the / for a //:
list = []
i = 17
for num in range(i):
list.append(num)
list = [x for x in list if x != 0]
for x in list:
product *= x
final = product + 1
final2 = final//i
if final2%1 == 0: #Here I have no idea of how to check if is a prime
print("Prime")
else:
print("Not prime")
I know this is not the best way to check if a number is prime.

Finding primes in python

I know that python is "slow as dirt", but i would like to make a fast and efficient program that finds primes. This is what i have:
num = 5 #Start at five, 2 and 3 are printed manually and 4 is a multiple of 2
print("2")
print("3")
def isPrime(n):
#It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.
i = 5
w = 2
while (i * i <= n): #You only need to check up too the square root of n
if (n % i == 0): #If n is divisable by i, it is not a prime
return False
i += w
w = 6 - w
return True #If it isn´t ruled out by now, it is a prime
while True:
if ((num % 2 != 0) and (num % 3 != 0)): #save time, only run the function of numbers that are not multiples of 2 or 3
if (isPrime(num) == True):
print(num) #print the now proved prime out to the screen
num += 2 #You only need to check odd numbers
Now comes my questions:
-Does this print out ALL prime numbers?
-Does this print out any numbers that aren't primes?
-Are there more efficient ways(there probably are)?
-How far will this go(limitations of python), and are there any ways to increase upper limit?
Using python 2.7.12
Does this print out ALL prime numbers?
There are infinitely many primes, as demonstrated by Euclid around 300 BC. So the answer to that question is most likely no.
Does this print out any numbers that aren't primes?
By the looks of it, it doesn't. However, to be sure; why not write a unit test?
Are there more efficient ways(there probably are)? -How far will this go(limitations of python), and are there any ways to increase upper limit?
See Fastest way to list all primes below N or Finding the 10001st prime - how to optimize?
Checking for num % 2 != 0 even though you increment by 2 each time seems pointless.
I have found that this algorithm is faster:
primes=[]
n=3
print("2")
while True:
is_prime=True
for prime in primes:
if n % prime ==0:
is_prime=False
break
if prime*prime>n:
break
if is_prime:
primes.append(n)
print (n)
n+=2
This is very simple. The function below returns True if num is a prime, otherwise False. Here, if we find a factor, other than 1 and itself, then we early stop the iterations because the number is not a prime.
def is_this_a_prime(num):
if num < 2 : return False # primes must be greater than 1
for i in range(2,num): # for all integers between 2 and num
if(num % i == 0): # search if num has a factor other than 1 and itself
return False # if it does break, no need to search further, return False
return True # if it doesn't we reached that point, so num is a prime, return True
I tried to optimize the code a bit, and this is what I've done.Instead of running the loop for n or n/2 times, I've done it using a conditional statements.(I think it's a bit faster)
def prime(num1, num2):
import math
def_ = [2,3,5,7,11]
result = []
for i in range(num1, num2):
if i%2!=0 and i%3!=0 and i%5!=0 and i%7!=0 and i%11!=0:
x = str(math.sqrt(i)).split('.')
if int(x[1][0]) > 0:
result.append(i)
else:
continue
return def_+result if num1 < 12 else result

Project Euler #7 Python

I'm having trouble with my code. The question is:
"By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?"
This is what it looks like:
div = 10001
i = 2
count = 0
prime = 0
now = []
while count < div:
for x in range (2,i+1):
if len(now) ==2:
break
elif i%x == 0:
now.append(x)
if len(now)==1:
prime = i
count += 1
now = []
i+=1
print(prime)
I have tried div up to 1000 and it seems to work fine(for div 1000 I receive 7919). However, when I try div = 10001 I get nothing, not even errors. If someone would help me out I would really appreciate it.
Thank you.
# 7 10001st prime
import itertools
def is_prime(n):
for i in range(2, n//2 + 1):
if n % i == 0:
return False
else:
continue
return True
p = 0
for x in itertools.count(1):
if is_prime(x):
if p == 10001:
print(x)
break
p += 1
Try this code:
prime_list = lambda x:[i for i in xrange(2, x+1) if all([i%x for x in xrange(2, int(i**0.5+1))])][10000]
print prime_list(120000)
Lambda in Python defines an anonymous function and xrange is similar to range, defining a range of integer numbers. The code uses list comprehension and goes through the numbers twice up to the square root of the final number (thus i**0.5). Each number gets eliminated if it is a multiple of the number that's in the range count. You are left with a list of prime numbers in order. So, you just have to print out the number with the right index.
With just some simple modifications (and simplifications) to your code, you can compute the number you're looking for in 1/3 of a second. First, we only check up to the square root as #Hashman suggests. Next, we only test and divide by odd numbers, dealing with 2 as a special case up front. Finally, we toss the whole now array length logic and simply take advantage of Python's break logic:
limit = 10001
i = 3
count = 1
prime = 2
while count < limit:
for x in range(3, int(i ** 0.5) + 1, 2):
if i % x == 0:
break
else: # no break
prime = i
count += 1
i += 2
print(prime)
As before, this gives us 7919 for a limit of 1000 and it gives us 104743 for a limit of 10001. But this still is not as fast as a sieve.
m=0
n=None
s=1
while s<=10001:
for i in range(1,m):
if m%i==0:n=i
if n==1:print(m,'is prime',s);s+=1
m+=1

Finding the largest prime number "within" a number

For this question, I need to find the largest prime number within a larger number. For the purpose of the example, let's say the larger number is "123456789", then some of the numbers I would have to check are 12, 456, 234567, etc.
I wrote some Python code to figure this out, but it is running very slow for the number I am trying to check. The actual number I am working with is about 10000 digits, so there are a lot of numbers I need to look at. Here is my code:
num = "123456789"
def isPrime(n):
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, long(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def largestPrime():
largest = 2
for i in range(0,len(num)):
for j in range(i+1,len(num)):
if isPrime(long(num[i:j])):
if long(num[i:j]) > largest:
largest =long(num[i:j])
print largest
def main():
largestPrime()
main()
I'm pretty sure this code gives the correct answer, but as I said, it's really slow. Can anyone help me figure out how to speed this up?
Thanks for any help!
I'd probably use the strategy of starting with the total number of digits and seeing if that's prime. Then keep decreasing the digits by one while shifting over to the left to see if that's prime. Let me explain with an example:
123456789
First check the 9-digit number: 123456789
Then check the 8-digit numbers: 23456789, 12345678
Then Check the 7-digit numbers: 3456789, 2345678, 1234567
etc.
One problem I see is that for some large numbers you are going to be testing the same number many times. For example for '123456712345671234567', your code will test '1234567' 3 times. I suggest you make a set that contains no duplicates, then run your prime test on each number. I also think that sorting the numbers is a good idea because we can stop after the first prime is found.
Next if you are dealing with large numbers (e.g. 10000 digits), I suggest using a statistical primality test. Below I made a Miller-Rabin primality test using pseudocode from wikipedia.
I have pretty much rewritten your code :P
import random
num = '3456647867843652345683947582397589235623896514759283590867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876784235876324650'
def probablyPrime(num, k):
"""Using Miller-Rabin primality test"""
if num == 2 or num == 3:
return True
if num < 2:
return False
if not num & 1:
return False
# find s and d such that n−1 = (2**s)*d with d odd
d = (num-1) >> 1
s = 1
while not (d & 1):
d = d >> 1
s += 1
# run k times
for _ in range(k):
a = random.randint(2, num-2)
x = pow(a, d, num) # more efficient than x = a**d % num
if not (x == 1 or x == num-1):
for _ in range(s-1):
x = (x**2) % num
if x == 1:
return False
if x == num-1:
break
if not x == num-1:
return False
return True
def largestPrime(num):
num_list = set([])
for i in range(0,len(num)+1):
for j in range(i+1,len(num)+1):
inum = int(num[i:j])
# Don't append numbers that have already appeared
if inum not in num_list:
num_list.add(inum)
# Convert to list and sort
num_list = list(num_list)
num_list.sort(reverse=True)
for num in num_list:
print('Checking ' + str(num))
if probablyPrime(num,100):
print('\n' + str(num) + ' is probably the largest prime!')
return
largestPrime(num)
Another way to improve speed might be python's multiprocessing package.
Code:
def isprime(n):
if n == 2:
return str(n)+" is the biggest prime"
if n % 2 == 0:
return isprime(n-1) #not prime, check again for next biggest number
max = n**0.5+1
i = 3
while i <= max:
if n % i == 0:
return isprime(n-1) #not prime, check again for next biggest number
i+=2
return str(n)+" is the biggest prime"
print "Testing 7:",isprime(7)
print "Testing 23:",isprime(23)
print "Testing 2245:",isprime(2245)
print "Testing 222457:",isprime(222457)
print "Testing 727245628:",isprime(727245628)
Output:
>>>
Testing 7: 7 is the biggest prime
Testing 23: 23 is the biggest prime
Testing 2245: 2243 is the biggest prime
Testing 222457: 222437 is the biggest prime
Testing 727245628: 727245613 is the biggest prime

Python output just shows blinking cursor

I recently started messing around with python and I wrote a program to print out the 1000th prime number but the output only shows a blinking cursor , the code is shown below:
number = 3
count= 1
while count <= 1000:
prime = True
for x in range(2, number):
if number % x == 0:
prime= False
if prime == True:
count = count + 1
if count <= 1000:
number = number + 1
print number
Any help and concise explanation would be appreciated
edit: i just realized the problem. #tichodroma solved the problem but did so by editing the OP post. so when i got to it it was already solved, how ever, he solved it by putting the print into the loop, hence the many numbers waterfall. but it should be outside the loop so as to only show the final result. also - after looking at the OP code before edit, it was written in such a way that it was taking a long time to run, and the "blinking line" was the system working in the background
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
counter = 0
number = 0
while True:
if isprime(number):
counter+=1
if counter == 10000:
break
number+=1
print number

Categories

Resources