I'm trying to find the largest prime factor of a given number (600851475143) using Python. I've made the following code, but I don't know what is wrong and whether I am using right code Please help find my mistake and improve it.
import math
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
print t(600851475143)
print check(486847)
You need to check that everything you're adding to the list is actually a prime
for i in range(1,int(math.sqrt(x))):
if (x % i) != 0:
continue
if check(i):
l.append(i)
Then, pop the last (largest) element of the list:
return l.pop()
You can also check up to the square root:
def check(y):
for i in range(2,int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
Here's a slightly modified version that iterates backwards (as suggested by pzp), and returns as soon as a prime is found:
#!/usr/bin/env python
import math
def t(x):
for i in xrange(int(math.sqrt(x)), 1, -1):
if (x % i) != 0:
continue
if check(i):
return i
return None
def check(y):
for i in range(2, int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
print t(600851475143)
print check(6857)
You're pretty close. Your check() is returning before you want it to. You want:
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
This will wait until you've check all the numbers < y before returning false. Right now, it checks 2, then returns either true or false.
Also t() is returning all factors, rather than the greatest factor. For just the greatest factor (assuming there is one), you want return l[-1]
EDIT:
Ok, I think I get what you're going for. By using this t() and check(), you can get the largest prime by with:
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
#Notice, return list of all factors
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return False
return True
number_to_check = 92873465
prime_factors = []
for factor in t(number_to_check): # Iterate through factors returned from t()
if check(factor):
prime_factors.append(factor)
print "Largest Prime Factor: " + prime_factors[-1]
Related
(I'm a total beginner)
I want to write a recursive function which can tell me if a number is a prime number or not: but I keep getting the same recursion error :
here is my code :
from math import *
def has_a_divider(n,p):
if n%p==0:
return True
elif has_a_divider(n,(p-1))!= True:
return False
else:
return False
def is_prime(a):
if has_a_divider(a,sqrt(a))==False:
return True
else:
return False
Your problem is sqrt(a) which returns a float instead of the int your code requires.
You can replace it by ceil(sqrt(a)) to get an int from it.
Also, this code does not work for finding if the number is prime as all numbers will have at least 1 has a divider. A possible solution is to update has_a_divider to check for dividers bigger than 1.
A possible implementation:
from math import ceil, sqrt
def has_a_divider(n,p):
if p < 2:
return False
if n % p==0:
return True
return has_a_divider(n,(p-1))
def is_prime(a):
if a == 1:
return False
return not has_a_divider(a,ceil(sqrt(a)))
print(is_prime(3))
print(is_prime(5))
print(is_prime(4))
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,4000000):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
What is wrong with this code? It does not return anything but it looks good according to me.
you should return sum(L) from function not from for loop follow below code
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,20):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
and other thing look at the range its too much,because of this it will take some time or may produce any memory related error, so reduce it for testing.
The return statement is set to the wrong increment. It is executed the first time i % 2 == 0 becomes true (which is i == 2 in your case).
def fib(n):
if n<= 1:
return n
else:
return(fib(n-1)+fib(n-2))
def comp():
L=[]
for i in range(1,4000000):
if i % 2 ==0:
L.append(fib(i))
return sum(L)
print(comp())
The above code is not going to work, though. Are you aware of how big this number would get?
Try
for i in range(1,40):
as a start. It took quite a few seconds on my machine. Result is 63245985.
I have an assignment I've been stuck on for a couple days now. I have to recursively figure out if a list has repeats but I cannot use any loops or built in functions besides len(). I'm also not allowed to use the 'in' function. Returns True if list L has repeats, False otherwise. This is what I've been able to figure out:
def has_repeats(L):
if len(L) <= 1:
return False
elif L[0] == L[1]:
return True
else: return has_repeats(L[0] + L[2:])
But the problem with that is it's only comparing the first element to the rest, instead of each element to the rest. I can't figure out how to do that without a running counter or something. Any suggestions?
You almost have it. Along with checking the first element with the rest of the list, you also need to check the second the same way:
def has_repeats(L):
if len(L) <= 1:
return False
if L[0] == L[1]:
return True
if has_repeats([L[0]] + L[2:]):
return True
if has_repeats(L[1:]):
return True
return False
You can also compact this into the following representation:
def has_repeats(L):
return len(L)>1 and L[0]==L[1] or has_repeats([L[0]]+L[2:]) or has_repeats(L[1:])
Use a helper function:
def helper(ele, rest):
if not rest:
return False
return ele == rest[0] or helper(ele, l[1:])
def has_repeats(l):
if not l:
return False
return helper(l[0], l[1:]) or has_repeats(l[1:])
guys!
I have a codecademy Python course excercise in which I have to check if parameter passed is prime. My code looks like this:
def is_prime(x):
for n in range(2, x-1):
if (x < 2):
return False
elif(x % n == 0):
return True
else:
return False
It seems to me that I have covered all possibilities, but it constatnly displays this error:
Your function fails on is_prime(0). It returns None when it should return False.
This falls in the first if-condition as far as I can see. Can someone explain how this is possible?
Hint, what numbers are inside range(2, x-1) when x is 0?
This version may works.
def is_prime(x):
if (x < 2):
return False
for n in range(2, x-1):
if(x % n == 0):
return False
return True
I'm trying to define a method to check whether or not every element of a list is a factor of the parameter.
Here's what I have:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(In this case nums is a list of the integers from 1 to 10)
However, this returns true for any number. I'm assuming this happens because it is only checking 1 and then returning True, but shouldn't all() be checking for every element of the list before returning True?
I'm a bit unfamiliar with all() so I probably implemented it incorrectly. Can someone point me in the right direction?
Thanks!
you should use not any instead of all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
or if you want it like you currently have it
def factorall(x):
return all(x%num==0 for num in nums)
You should do the comparison inside the all function, or simply remove it, and use negation of the result x % num:
def factorall(x):
return all(not x % num for num in nums)
The return statement works same as:
return all(x % num == 0 for num in nums)
I agree that the 2nd one seems clearer.
def factorall(x):
if all(x % num == 0 for num in nums):
return True
else:
return False