I'm creating a Goldbach conjecture which outputs the two prime numbers with the highest product. As it stands once the input is a large number, it takes a ridiculously long time to solve.
def prime_pair_solution(n):
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
k= int(n**0.5)+1
for x in range(3, k, 2):
if n % x == 0:
return False
return True
count=(int(n/2)+(int(n/4)))
y=[(p2,p1)for p1 in range (2,count) for p2 in range(p1,count) if isprime(p1) and isprime(p2) and (p1+p2)==n]
return y[-1]
Related
The following program, balanced_centrifuge(), takes positive integers (n, k), where k <= n, and determines whether k and n-k can be expressed as a sum of the prime factors of n (note, repetition of factors is allowed). I've been able to walk through the logic of this code and it makes sense, but the runtime is over 20 seconds which is too slow for my tester. It works for all the suggested test cases however, (6,3), (7,0), (15,8), (222, 107), and (1234, 43). Where is the slowdown occurring?
import itertools
def balanced_centrifuge(n,k):
if n == 1:
return False
if k == 0 or n - k == 0:
return True
primes = get_primes(n)
final_answer = is_sum(primes, k) and is_sum(primes,n-k)
return final_answer
def get_primes(n):
i = 2
factors = []
while i * i <= n:
if n % i != 0:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def is_sum(primes, goal):
if primes == []:
return False
for i in range(goal//primes[0]+1, 0, -1):
ans = itertools.combinations_with_replacement(primes, i)
for comb in ans:
#print(comb)
# single tuple with i elements to try
if sum(comb) == goal:
return True
return False
I'm learning Python by doing Project Euler questions and am stuck on Problem #3.
I think I've found a solution that works, but when inserting the large number 600851475143 it just doesn't return anything. I believe that it just loads and loads cause even with 6008514 it takes 10 secs to return the answer.
# What is the largest prime factor of the number x?
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
for n in range (2 , int(sqr)+1):
if x % n == 0:
return 0
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
else:
largest = -1
mid = x/2
for n in range(2,int(mid)+1):
if isPrime(n):
if x % n == 0:
largest = n
if largest == -1:
return 'Enter numbers above 1.'
else:
return largest
print(largestPrimeFactor(600851475143))
This code should work:
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
n = 2
highest = x
while n < highest:
if x%n ==0:
return 0
highest = x/ n
n +=1
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
n = 2
highest = x
largest = 1
while n < highest:
if x%n == 0:
if isPrime(n):
largest = n
highest = x/n
n +=1
return largest
print(largestPrimeFactor(600851475143))
I made an optimization:
you check if every number is a factor of x while if for example 2 is not a factor of x for sure the maximum factor of x can be x/2. Hence if n is not a factor of x the maximum possible factor of x can just be x/n.
The code for large numbers just takes really long time, as pointed out by comments. I report other bugs.
Bug 1. Inappropriate use of try/except clause. It is recommended that try contains a single command and except catches the error. PEP8 also recommends specifying the type of error. Moreover, for your function, the error is never raised.
Bug 2. Redundancy. If x is not prime, you call isPrime for each value (let's call it i) from 2 to x/2. isPrime cycles for each number from 2 to sqrt(i). Therefore, isPrime(i) takes O(sqrt(i)) time, and we call it for i from 2 to x/2. Roughly, its running time is about O(x^(3/2)). Even if don't know a more optimal approach, this approach asks for memoization.
i have another way:
def Largest_Prime_Factor(n):
prime_factor = 1
i = 2
while i <= n / i:
if n % i == 0:
prime_factor = i
n /= i
else:
i += 1
if prime_factor < n:
prime_factor = n
return prime_factor
it faster than previous
try it:
import math
def maxPrimeFactors (n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
n = 600851475143
print(maxPrimeFactors(n))
Can somebody solve this problem on Python ?
A positive integer m can be partitioned as primes if it can be written as p + q where p > 0, q > 0 and both p and q are prime numbers.
Write a Python function that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise.
Tried this, but does not work for all testcases, for example it should return True for 3432, it returns False.
def partition(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
y= num-x
for z in range(2,y):
if y%z == 0:
return False
return True
The error lies in the second for loop. You are looping through possible primes x, and wish to then check that y = num - x is also prime.
The error in your logic is that in the second for loop, if the first element in the loop y = num - x is not prime, it will return False, without checking any of the other possible values.
You could correct this by moving the return False statement out one loop, but since you have already generated a list of primes less than num, primelist (and since y = num - x, (if prime y exists) it will be in this list), you can just check for membership of the list:
for x in primelist:
y= num-x
# Note: num = x + y, thus need only check y prime
if y in primelist:
return True
# If no such y is prime, not possible
else:
return False
Note: I would advise making the logic of your script more modular, separating out the prime list generator into its own function:
def partition(num):
"""
Return True if there exist primes x,y such that num = x + y.
Else return False.
"""
primelist = primes(num)
for x in primelist:
y= num-x
# Note: num = x + y, thus need only check y prime
if y in primelist:
return True
# If no such y is prime, not possible
else:
return False
def primes(num):
"""Return list of all primes less than num."""
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
return primelist
final solution i got:
def primepartition(m):
primelist=[]
if m<0:
return False
else:
for i in range(2,m + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
y= m-x
if y in primelist:
return True
return False
The given below code can hopefully give you the correct output.
def factors(n):
factorslist = []
for i in range(1, n+1, 1):
if n % i == 0:
factorslist.append(i)
return(factorslist)
def prime(n):
if factors(n) == [1, n] and n > 1:
return(True)
def primelist(n):
primenolist = []
for i in range(1, n+1, 1):
if prime(i) == True:
primenolist.append(i)
return(primenolist)
def primepartition(m):
if m > 0:
primenolist = primelist(m)
checklist = []
for p in primenolist:
q = m - p
if q in primenolist and p > 0 and q > 0:
checklist.append((p,q))
if len(checklist) > 0:
return(True)
else:
return(False)
else:
return(False)
Another approach,
Initially, we store all prime elements upto m and check for pair of primes whose sum equal to m
def primepartition(a):
l=[2]#since 'a' should be >=2 for below loops, we took here 2(1st prime).
for i in range(2,a):
flag=0
for j in range(2,i):
if i%j==0:
flag=0
break
else:
flag=1
if flag==1:
l.append(i)
for i in l:
for j in l:
if i+j==a:
return True
return False
n=int(input("Enter any number: "))
list=[]
for num in range(0,n + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
list.append(num)
if (n<= 1):
print("False")
#print("It is not positive ")
else:
for i in list:
y = num -i
if (y in list):
print("True")
#print(y,"+",i,"=",n)
#print(i,"+",y,"=",n)
#print("The number can be expressed as the sum of two prime numbers.")
break
else:
print("False")
#print("The number can not be expressed as the sum of two prime numbers.")
Slight Variation of your code:
def primepartition0(m):
primelist=[]
if m<0:
return False
else:
for i in range(2,m + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
for y in primelist:
if x != y and x+y == m:
return True
return False
An alternate approach that attemps to reduce the amount of code necessary:
def primepartition(m):
if m > 3:
for number in range(m // 2, m - 1):
difference = m - number
for psuedoprime in range(2, int(number ** 0.5) + 1):
if number % psuedoprime == 0 or difference > psuedoprime and difference % psuedoprime == 0:
break
else: # no break
return number, difference # as good a non-False result as any other...
return False
def factors(n):
factlist = []
for i in range(1,n+1):
# Since factors of 2 cannot be primes, we ignore them.
if n%i==0 and i%2!=0:
factlist.append(i)
return factlist
def isprime(n):
return(factors(n)==[1,n])
def preimesupto(n):
primelist = []
if n>=2:
primelist.append(2)
for i in range(n):
if isprime(i):
primelist.append(i)
return primelist
def primepartition(n):
if n<0:
return False
primelist = preimesupto(n)
for i in primelist:
j = n-i
if j in primelist:
return True
else:
return False
If you're not required to produce the actual primes but only test if there exists a pair of primes p and q such that p+q == N, you could make this very simple based on the Goldbach conjecture. All even numbers can be expressed as the sum of two primes. So return True if the number is even and check if N-2 is prime for odd numbers (because 2 is the only even prime and that's the only prime that will produce another odd number when starting from an odd number). This will boil down to a single prime test of N-2 only for odd numbers.
def primePart(N):
return N%2==0 or all((N-2)%p for p in range(3,int(N**0.5)+1,2))
primePart(3432) # True
primePart(37+2) # True
primePart(13+41) # True
primePart(123) # False
If you want to actually find a pair of primes that add up to N, you can generate primes up to N and return the first prime >= N/2 where N - prime is one of the primes already found:
def findPQ(N):
if not primePart(N): return
if N%2: return 2,N-2
isPrime = [0]+[1]*N
for p in range(3,N,2):
if not isPrime[p]: continue
if 2*p>=N and isPrime[N-p]: return p,N-p
isPrime[p*p::p] = [0]*len(isPrime[p*p::p])
output:
findPQ(3432) # (1723, 1709)
findPQ(12345678) # (6172879, 6172799)
To go beyond 10^9 you will need a more memory efficient algorithm than the sieve of Eratosthenes that is just as fast. This can be achieved with a dictionary of multiples of primes to skip:
def findPQ(N):
if not primePart(N): return
if N%2: return 2,N-2
skip,primes = {},{2}
for p in range(3,N,2):
if p in skip:
prime = skip.pop(p)
mult = p + 2*prime
while mult in skip: mult += 2*prime
if mult <= N: skip[mult] = prime
else:
if 2*p>=N and N-p in primes: return p,N-p
if p*p<=N: skip[p*p]=p
if 2*p<=N: primes.add(p)
output (takes a while but doesn't bust memory space):
findPQ(1234567890) # (617283983, 617283907)
def checkprime(number):
fact=1
for r in range(2,number):
if number%r==0:
fact=fact+1
return(fact<2)
def primepartition(m):
for i in range(2,m):
flag=0
if checkprime(i) and checkprime(m-i)==True:
flag=1
break
return(flag==1)
def matched(s):
list_of_string=list(s)
for y in range(len(list_of_string)):
if list_of_string[y]=='(':
for z in range(y,len(list_of_string)):
if list_of_string[z]==')':
list_of_string[y]='#'
list_of_string[z]='#'
break
return('('not in list_of_string and ')'not in list_of_string)
def rotatelist(l,k):
if k>len(l):
k=int(k%len(l))
return(l[k:]+l[0:k])
I have written the below code in python to print out prime numbers but its giving output like:
3,5,7,**9**,11,13,**15**,17,19,**21**,23,25............99
below is the code:
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n = 1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
You are returning True after the number fails to be divisible by one number. You need to return true after you have checked all the numbers. Instead, you should write
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
return True
One other note: if you are testing for prime numbers, you only need to test up to the square root of the number. If the number is not divisible by any numbers less than its square root, then it is also is not divisible by any that are greater and thus must be prime. This will help make your code more efficient.
Your isprime function says:
for x in range(2, n):
if n % x == 0:
return False
else:
return True
This means that on the first iteration (when x==2), if n%x is not zero, it will return True. So it will return True for any odd number (above 1, which you skipped).
Instead, you want to return True if none of the numbers in the loop were factors.
for x in range(2, n):
if n % x == 0:
return False
# the loop finished without returning false, so none of the numbers was a factor
return True
I am new to Python. I am using python 2.7.3 and I have written a small function to check if the given number is prime or not.
The code is as follows -
#!/usr/bin/python2.7
def isprime(n):
if n == 1:
print("1 is neither Prime nor Composite.")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print("{} is a prime number".format(n))
return True
for n in range(1, 5):
isprime(n)
And the output is -
1 is neither Prime nor Composite.
3 is a prime number
4 equals 2 x 2
Why is it escaping 2. I tried debugging as well but its simple bypassing 2.
Thanks.
Think about the case where n == 2:
def isprime(n):
if n == 1: # nope
...
for x in range(2, n): # here we go
So what actually happens?
>>> range(2, 2)
[]
Nothing; you are iterating over an empty range.
Also, you have a logic error - you return True if the first value in range(2, n) (i.e. 2) isn't an integer divisor of n - you claim than any odd number is prime:
>>> isprime(9)
9 is a prime number
True # what?!
If you dedent the last three lines by one level, it fixes both issues:
def isprime(n):
if n == 1:
print("1 is neither Prime nor Composite.")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print("{} is a prime number".format(n))
return True
(alternatively, leave out the else and dedent the last two lines a further level). This gives me:
>>> isprime(9)
9 equals 3 x 3
False
>>> isprime(2)
2 is a prime number
True
If n is 2, then on the line for x in range(2, n): the range(2, 2) will return an empty list.