how to fix ' find the prime factors of a number' in Python - python-3.x

I tried to find the prime factor for a number by the following code:
def pf(n):
f=[]
while n != 1:
for i in range(2, n+1):
if n%i == 0:
f.append(i)
n //=i
return f
The output for pf(8) is [2, 4], rather than [2,2,2] as my expect.
The output for pf(16) is [2,4,2], rather than [2,2,2,2].
can anyone help me to figure out what's wrong with my code?

If you break inside the loop, you will get what you want :
def pf(n):
f=[]
while n != 1:
for i in range(2, n+1):
if n%i == 0:
f.append(i)
n //=i
break
return f
Why was it wrong ?
in you first for loop, 8 is can be divied by 2, so n is equal to 4. And when i is then equals to 4, then 4 is added as a prime factor
Other implementation:
I prefer this implementation :)
def pf(n):
f=[]
i = 2
while n != 1:
if n%i == 0:
f.append(i)
n //=i
else:
i += 1
return f
This implementation avoids you to recompute the numbers in range you already know is not dividable by.

Related

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million

sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.
Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5+1)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
What about about this:
def isPrime(x):
prime = True
for i in range(2, x):
if x % i == 0:
prime = False
break
else:
continue
return prime
primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922
This code will take a few minutes to execute. Buckle up!!
def sumPrimes(n):
sum =0
for i in range(2 ,n):
for j in range(2, int(i / 2) +1):
if (i % j) == 0:
break
else:
sum += i
return sum
print(sumPrimes(2000000))
If you iterating over all numbers below 2 million, you might as well sieve them using the Sieve of Eratoshenes:
from math import ceil, sqrt
def sieve(n):
nums = list(range(2,n+1))
primes = []
p = 2
k = 1+ ceil(sqrt(n))
while p < k:
primes.append(p)
nums = [num for num in nums[1:] if num % p > 0]
p = nums[0]
return primes + nums
Then sum(sieve(2000000)) evaluates to 142913828922. It takes about 5 seconds to run on my machine.

Time limit exceeded python

Im a newbie at python and i have a task. Given a number as input, i have to print the prime that belongs in the number/position on a list of primes starting from position 1 and not 0, until the input is 'END'. For example, if the input is 1, output should be the first prime which is 2, if the input is 5, output should be the 5th prime which is 11 and so. It works fine but after 3/4-digit numbers the output has a delay until i get the Error: Time limit exceeded. How can i make it run faster? Here's the code:
def primes_function(n):
primes = []
num = 2
while len(primes) <= n:
x = num // 2
while x > 1:
if num % x == 0:
break
x -= 1
else:
primes.append(num)
num += 1
return primes[n - 1]
#main
while True:
n = input()
if n == 'END':
break
elif n > '0':
n = int(n)
value = primes_function(n)
print(value)
Sorry if i made any mistakes in the description
enter image description here
I combined this answer (1) and this answer (2) to speed up the function. The two key ideas are: When testing primality of a candidate ...
... do not divide by every number (2, 3, 4, 5, 6, ...) but only by the preceding prime numbers (2, 3, 5, ...). Every non-prime number > 2 is has to have some prime factor.
... divide only by numbers that are ≤ sqrt(candidate).
import math
def nth_prime(n):
prime_list = [2]
candidate = 3
while len(prime_list) < n:
max_factor = math.sqrt(candidate)
is_prime = True
for p in prime_list:
if p > max_factor:
break
elif candidate % p == 0:
is_prime = False
break
if is_prime:
prime_list.append(candidate)
candidate += 2
return prime_list[-1]
Benchmark of different solutions:
n=9000 n=15000 n=25000 n=75000
your solution 1m38.455s - - -
linked answer (1) 0m 2.954s 8.291s 22.482s -
linked answer (2) 0m 0.352s 0.776s 1.685s 9.567s
this answer 0m 0.120s 0.228s 0.410s 1.857s
Brij's answer 0m 0.315s 0.340s 0.317s 0.318s
For every n the programs where started from scratch.
As we can see, Brij's Sieve Of Eratosthenes takes a fairly low constant amount of time. If you want to find big prime numbers below a fixed limit then that's the best solution (here n < 78499, as the 78499-th prime number is 1 000 003 which is bigger than the sieve list).
If you also want to find a lot of smaller or medium sized prime numbers or cannot accept a fixed limit then go with this solution.
def SieveOfEratosthenes():
n = 1000000
prime = [True for i in range(n+1)]
p = 2
count = 0
while (p * p <= n):
if (prime[p] == True):
count = count + 1
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
seive = []
for p in range(2, n):
if prime[p]:
seive.append(p)
return seive
def primes_function(n , seive):
return seive[n - 1]
#main
seive = SieveOfEratosthenes()
while True:
n = input()
if n == 'END':
break
elif n > '0':
n = int(n)
value = primes_function(n,seive)
print(value)
Full working : https://ide.geeksforgeeks.org/QTSGQfhFV3
I have precomputed the primes below 10^6 and made a list of primes and accessed the nth prime number by the index.

Finding the logical error in my code to get first 50 primes

I'm trying to write my own formula to find a prime number, but it does not completely work and I cannot find the flaw in my logic. Bare in mind I have taken a look around but cannot find an algorithm that I find similar to mine.
My code:
#Challenge 7
prime = []
num = 0
found = False
while found == False:
if num == 0 or num == 1:
num+=1
else:
for value in range(2, num+1):
if len(prime) == 50:
print('Found all')
found = True
break
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
print(prime)
This code works for first few primes (3, 5, 7...)
but it also gives incorrect values like 10, and I don't understand why. If someone could explain it to me so that I can understand where the logical mistake is, I'd appreciate it.
The error comes from this part
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
You assume that the integer is a prime as soon as we find the first occurence of a non-divisor. But the def for primes is that every integer in the interval [2..prime] is a non-divisor. How do we check if any number does not have any divisors?
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
Something like this would work to check if any given number is a prime or not. And since we now have taken the isPrime part out of the main loop, we no longer need a for loop inside the while. Something like this would do
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
prime = [}
num = 2
found = False
while found == False:
if len(prime) == 50:
print("found all")
found = True
break
if(isPrime(num)):
print(num)
prime.append(num)
num+=1
else:
num+=1
If you set a breakpoint for when num == 10 you will see the problem clearly.
When you start doing you division check inside of for value in range(2, num + 1): the second number is 3, so num (10) modulo value (3) is 1, which is your test for determining a prime. What your test should be is that it not divisible by any number less than it (less than half is actually sufficient since you check with 2 anyway).
So, consider instead:
else:
is_indivisible = True
# loop through all numbers less than it not including itself
# (because x % x == 0)
for value in range(2, num - 1):
# it is only indivisible if it was previously indivisible
# And the check is same as before, modulo != 0
is_indivisible = is_indivisible and (num % value != 0)
if not is_indivisible:
break
# if it is indivisible and it doesn't exist in prime list yet
if is_indivisible and num not in prime:
prime.append(num)
# move on to the next number
num += 1

Using Recursive Functions in Python to find Factors of a Given Number

Have tried searching for this, but can't find exactly what I'm looking for.
I want to make a function that will recursively find the factors of a number; for example, the factors of 12 are 1, 2, 3, 4, 6 & 12.
I can write this fairly simply using a for loop with an if statement:
#a function to find the factors of a given number
def print_factors(x):
print ("The factors of %s are:" % number)
for i in range(1, x + 1):
if number % i == 0: #if the number divided by i is zero, then i is a factor of that number
print (i)
number = int(input("Enter a number: "))
print (print_factors(number))
However, when I try to change it to a recursive function, I am getting just a loop of the "The factors of x are:" statement. This is what I currently have:
#uses recursive function to print all the letters of an integer
def print_factors(x): #function to print factors of the number with the argument n
print ("The factors of %s are:" % number)
while print_factors(x) != 0: #to break the recursion loop
for i in range(1,x + 1):
if x % i == 0:
print (i)
number = int(input("Enter a number: "))
print_factors(number)
The error must be coming in either when I am calling the function again, or to do with the while loop (as far as I understand, you need a while loop in a recursive function, in order to break it?)
There are quite many problems with your recursive approach. In fact its not recursive at all.
1) Your function doesn't return anything but your while loop has a comparision while print_factors(x) != 0:
2) Even if your function was returning a value, it would never get to the point of evaluating it and comparing due to the way you have coded.
You are constantly calling your function with the same parameter over and over which is why you are getting a loop of print statements.
In a recursive approach, you define a problem in terms of a simpler version of itself.
And you need a base case to break out of recursive function, not a while loop.
Here is a very naive recursive approach.
def factors(x,i):
if i==0:
return
if x%i == 0:
print(i)
return factors (x,i-1) #simpler version of the problem
factors(12,12)
I think we do using below method:
def findfactor(n):
factorizeDict
def factorize(acc, x):
if(n%x == 0 and n/x >= x):
if(n/x > x):
acc += [x, n//x]
return factorize(acc, x+1)
else:
acc += [x]
return acc
elif(n%x != 0):
return factorize(acc, x+1)
else:
return acc
return factorize(list(), 1)
def factors(x,i=None) :
if i is None :
print('the factors of %s are : ' %x)
print(x,end=' ')
i = int(x/2)
if i == 0 :
return
if x % i == 0 :
print(i,end=' ')
return factors(x,i-1)
num1 = int(input('enter number : '))
print(factors(num1))
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutations, variable reassignments, and other side effects. That said, here's how I'd write factors -
def factors(n, m = 2):
if m >= n:
return
if n % m == 0:
yield m
yield from factors(n, m + 1)
print(list(factors(10))) # [2,5]
print(list(factors(24))) # [2,3,4,6,8,12]
print(list(factors(99))) # [3,9,11,33]
And here's prime_factors -
def prime_factors(n, m = 2):
if m > n:
return
elif n % m == 0:
yield m
yield from prime_factors(n // m, m)
else:
yield from prime_factors(n, m + 1)
print(list(prime_factors(10))) # [2,5]
print(list(prime_factors(24))) # [2,2,2,3]
print(list(prime_factors(99))) # [3,3,11]
def fact (n , a = 2):
if n <= a :
return n
elif n % a != 0 :
return fact(n , a + 1 )
elif n % a == 0:
return str(a) + f" * {str(fact(n / a , a ))}"
Here is another way. The 'x' is the number you want to find the factors of. The 'c = 1' is used as a counter, using it we'll divide your number by 1, then by 2, all the way up to and including your nubmer, and if the modular returns a 0, then we know that number is a factor, so we print it out.
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)

Finding largest prime factor too slow in Python

Question:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
And I tried to solve it by using the below snippet, its taking long time to run. Is there any best way to solve this problem?
def find_prime(num, ranger):
count = 0
prime = True
for i in range(2, num):
if num % i == 0:
count = count + 1
if count > 1:
prime = False
return prime
return prime
prime_list = []
target = 600851475143
for i in range(2,target ):
if target % i == 0:
print(i)
if find_prime(i,target) and i % 2 == 0:
prime_list.append(i)
print(prime_list)
print(max(prime_list))
Please suggest.
n=600851475143
d=2
while d < n/d:
if n%d==0:
n/=d
else:
d+=1
print n

Resources