Even valued terms sum in fibonacci, limit is 4 million - python

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.

Related

Python RecursionError

(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))

Fibonacci summing and memoization [duplicate]

This question already has answers here:
Sum of Even Fibonacci Numbers < X
(5 answers)
Closed 2 years ago.
I'm taking a programming course and there's a question about fibonacci sums and recursion.
the rules are as follows:
Write a function fibsum(N) that returns the sum of all even valued fibonacci terms that are less than N.
I've gotten close I think but my summation isn't working properly, also I'd like the function to work up pretty high (like N = 10**6 at least), here's my code so far
def fibsum(n, memo = {}):
added = 0
if n<0:
return 0
if n== 1 or n == 0:
return 1
else:
if (n-1) in memo.keys():
f1 = memo[n-1]
else:
memo[n-1] = fibsum(n-1)
f1 = memo[n-1]
if (n-2) in memo.keys():
f2 = memo[n-2]
else:
memo[n-2] = fibsum(n-2)
f2 = memo[n-2]
if f1+f2 < 44:
if (f1+f2) % 2 == 0:
added += f1+f2
print ("look here",added)
return added
print (f1+f2)
return f1 + f2
I've left some print statements because I was trying to debug the problem but I've had no luck.
edit: I've been linked another question but it is done iteratively in that case, I would like to do it recursively if possible
memoization wont help you with large values for fib
but as an aside seperate your logic
def fib(n):
"""
simple recursive fibonacci function
"""
if n == 0:
return 1
return n + fib(n-1)
then make a generic memoization decorator
def memoize(fn):
cache = {}
def _tokenize(*args,**kwargs):
return str(args)+str(kwargs)
def __inner(*args,**kwargs):
token = _tokenize(*args,**kwargs)
if token not in cache:
cache[token] = fn(*args,**kwargs)
return cache[token]
now just decorate your simple recursive function
#memoize
def fib(n):
"""
simple recursive fibonacci function
"""
if n == 0:
return 1
return n + fib(n-1)
now you can make your fibsum method (and also memoize it)
#memoize
def get_fib_nums(n):
if n == 0:
return [1]
return [n] + get_fib_nums(n)
#memoize
def fibevensum(n):
return sum(n for n in get_fib_nums(n) if n%2 == 0)

Largest prime factor-Python

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]

Maximum recursion, GCD(greatest common divisor)

I wrote a program to find gcd using python.
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
else:
gcd(a,b)==gcd(b,r)
return gcd(b,r)
Whenever I call the function it shows the message "Max. recursion exceeded." Please help
I know it can be done using looping but I want to specifically do it by using recursion method. And bear with me. I am a learner!
This statement is unnecessary and it's the one making the recursion endless: gcd(a,b)==gcd(b,r) because it's calling gcd(a,b) again and again. Just remove it:
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
return gcd(b,r)
Note: By the way, you got the formula wrong, you should return b on the if clause since you're dividing a/b when calculating the modulo.
def gcd(a,b):
r=a%b
if r==0:
return b
elif r==1:
return 1
return gcd(b,r)
>>>gcd(10,4)
2
If you're trying to calculate the GCD of very large numbers (e.g., when searching for common factors in RSA moduli), you might be better off avoiding recursion altogether and using an iterative function instead. For example:
def gcd(a,b):
while a:
a,b = b%a,a
return b
gcd(a,b)==gcd(b,r) doesn't do what you expect it to do.
It doesn't mean "define gcd(a,b) to be equal to gcd(b,r)".
Instead, gcd(a,b)==gcd(b,r) means:
Compute gcd(a,b)
Compute gcd(b,r)
Compare the two results and see if they're equal.
Since you're asking to compute gcd(a, b) in order to compute gcd(a, b), you'll get an endless recursion.
Instead, you want the return gcd(b, r) at that point. I.e.:
def gcd(a,b):
r=a%b
if r==0:
return a
elif r==1:
return 1
else:
return gcd(b,r)
This is how I did it
def gcd(m,n):
if m >= n:
r = m % n
if r == 0:
return n
else:
m = n
n = r
return gcd(m,n)
else:
temp = m
m = n
n = temp
return gcd(m,n)
def gcd(a,b):
if a % b == 0:
return b
return gcd(b, a % b)

Trying to check a condition for every element in a list of integers

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

Categories