Iterating through the Fibonacci sequence - python

so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
which returns the fibonacci number for any given input. this bit seems to work OK. However, I'd like to include a couple of conditions, like even numbers and F(n) below a certain limit. I tried using an if loop like this:
def ser():
count = 0
for i in F(n):
if F(n) <= 4000000 and F(n) % 2 == 0:
count = count + F(n)
But it seems like you can't use F(n) in the iteration for loop like I did. I'm a complete novice at python, so how would be best to use the F(n) function I created to iterate over the sequence? Thanks

What is the range of n that you are looking to run the fibonacci number on?
Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:
import itertools
count = 0
for n in itertools.count(1):
if F(n) > 4000000:
break
if F(n) % 2 == 0:
count += F(n)
You can use a generator form of fibonacci and use itertools.takewhile() to limit the output:
def F():
a,b = 0,1
yield b
while True:
a, b = b, a + b
yield b
count = sum(f for f in it.takewhile(lambda x: x <= 4000000, F()) if f % 2 == 0)

Related

How do I write a function that finds the sum of factorial of even numbers?

I've got a question- how do I write a function sum_even_factorials that finds the sum of the factorials of the even numbers that are less than or equal to n.
Eg:
sum_even_factorials(1)=
1
sum_even_factorials (3)=
3
sum_even_factorials (6)=
747
This is my current code:
Is there a logical error in the current code?
Is there a logical error in the current code?
To begin with, function sum_even_factorial doesn't return a value in every execution flow:
if cond1:
return val1
elif cond2:
return val2
else: # this part is missing in your code
return val3
In addition, note that when you call this function, you are not doing anything with the value that it returns:
sum_even_factorial(6)
Finally, although parts of your code are not visible in your question, I tend to guess that you cannot recursively compute the factorials of even numbers the way you did it, because the factorial of an even number n depends on the factorial of the odd number n - 1.
I think the code needs a loop. I'd write it like so:
def factorial(n):
if n == 0 or n == 1:
return 1;
else:
return n * factorial(n-1)
def sum_even_factorial(n):
current_sum = 0
while n >= 0:
if n % 2 == 0:
current_sum += factorial(n)
n -= 1
return current_sum
print(sum_even_factorial(6))
If you return tuples from the function, you can do it with one single function. See the comments in the code on how it works ...
def factorial_with_sum(n):
if n < 2:
return 1, 0 # first item of the tuple is the factorial, second item is the sum
else:
f, s = factorial_with_sum(n - 1) # calc factorial and sum for n - 1
f = f * n # factorial = n * factorial (n - 1)
if n % 2 == 0:
s = s + f # if n is even, add the current factorial to the sum
return f, s
fact, sum = factorial_with_sum(6)
print(fact)
print(sum)
You can also do it iteratively with a simple for loop as follows
def factorial_with_sum_iterative(n):
s = 0 # initialize sum
f = 1 # and factorial
for i in range(2, n + 1): # iterate from 2 to n
f = f * i # calculate factorial for current i
if i % 2 == 0:
s = s + f # if current i is even, add it to sum
return f, s

a (recursive) function that will calculate sum for a given n

How to write a recursive function that will calculate this sum for a given n?
n
∑ 1/k
k=1
My code:
def sum(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return sum(1/n) + sum(1/n+1)
print(sum(3))
For n = 3 the output should be: 1.8333333333333333
You should avoid declaring a new function with the name sum as there already exists a built-in function with this name.
You can recursively calculate
n n-1
∑ 1/k == 1/n + ∑ 1/k
k=1 for n > 0 k=1
with
def my_recursive_sum(n):
if n <= 0:
return 0
if n == 1:
return 1
return 1/n + my_recursive_sum(n-1)
print(my_recursive_sum(3))
Your solution would easily reach the maximum recursion limit.
when you call again the function using 1/n and 1/n+1 you would use the same n and increase it, so you would never reach the end condition.
the next couple of sum would never have an n value equal to 0 or 1.
Also you should not call again the function with 1/n otherwise you would endup looping forever in the function recall
you should use something like:
>>> def my_sum(n):
... if n < 1:
... return 0
... return 1/n + my_sum(n-1)
...
>>> print(my_sum(3))
1.8333333333333333
>>> 11/6
1.8333333333333333
>>>
edit:
Like mentioned in another answer you should avoid using sum as a name of a function because it's a name already use by python

Proper Carmichael Function

I'm creating all the necessary functions for RSA algorithm. Unfortunately i can't seem to a make proper Carmichael function.
These are the functions that i've written:
def gcd(a, b): # Greatest Common Divisor Generator (Euclidean Algorithm)
while b != 0: # While remainder exists
t = b # Initially r[k-1]
b = a % t # Initially r[k] = r[k-2] mod r[k-1] (where r[k-2] is a)
a = t # Predecessor of remainder (b)
return a
def phi(n): # Leonard Euler's Totient Function
y = 0
for k in range(1, n + 1): # Phi(+n) is the number of integers k in the range (1 <= k >= n)...
if gcd(n, k) == 1: # for which gcd(n, k) = 1
y += 1
return y
def carmichael(n): # Robert Daniel Carmichael's Function
y = (phi(n) * 1/2) if (n > 4 and ((n & (n - 1)) == 0)) else phi(n) # phi(n) * 1/2 if 2^x = n, else phi(n) * 1
return y
I'm using totient function for number generation. From my knowledge there is a simple rule, If number is power of 2 and it's greater than 4, Amount of it's prime numbers shall be halved, otherwise it's equal to phi(n).
The rule above is perfectly working in my code, For example, if the input value is 8, these are the results:
phi(8) = 4
carmichael(8) = 2
But the problem is, Carmichael function is also halving other numbers for some reason, for example if input is 12, this is what my functions return:
phi(12) = 4
carmichael(12) = 4
But this is how it should look like:
phi(12) = 4
carmichael(12) = 2
Why is this happening? Perhaps non-prime odd numbers should be treated differently? Is there something that i need to add to my function?
Thank you!
First we create the gcd function to calculate greatest common divisor of 2 numbers, we will need it later in lambda function.
def gcd(a,b):
while (a>0):
b=b%a
(a,b)=(b,a)
return b
Then we look at how carmichael function works.
Let n be a positive integer. Then λ(n) is defined to be the smallest positive integer k such that
a^k≡1(mod n)
for all a such that gcd(a,n)=1.
Note that we are looking for k, the values of a is determined once we have n.
Now we initialize the function with default condition
n=int(n)
k=2
a=1
alist=[]
To find all a values we use gcd(a,n)=1 to test whether a and n have the greatest common divisor as 1, which means they are coprime.
If not, a++
if gcd(a,n)==1, we store this value to the list of a and test next a until we test all a<=n
while not ((gcd(a,n))==1):
a=a+1
while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1
Ok now we have all a in the list alist, look back at definition
the smallest positive integer k such that
a^k≡1(mod n)
First we count the number of a, which is the length of alist
timer=len(alist)
Then we use
if (a**k)%n==1:
to test whether this k makes a^k≡1(mod n) for all a value in alist. We construct a loop
for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1
to test all k number from 2, if it doesnot meet requirement, we do k=k+1
Now we have the whole function as following
def carmichael(n):
n=int(n)
k=2
a=1
alist=[]
while not ((gcd(a,n))==1):
a=a+1
while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1
timer=len(alist)
while timer>=0:
for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1
return k

a recursive function to calculate sum of a number digits

i have to write a recursive function which calculates sum of a number digits,here's the code i tried :
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
while n > 0 :
sum = sum + sum_digit(n)
return sum
print(sum_digit(67154))
i don't know why i don't get the 23 as answer...my program doesn't come to an end
for example 23 number(please correct me if I'm wrong,I'm a newbie in python),the 3 goes to sum, and n become2,since its > 0 then it should go to while,so now it should calculate sum digit(2),the a become 2 and 2 goes to sum and n become 0 and sum digit(2) returns 2,then it sum with the 3 and i must get 5.
i appreciate your help.
You have an infinite loop because n never changes within the loop. Note that assigning a new value to n in the scope of the called function will not change n in the outer scope.
Also, it seems you are mixing an iterative solution with a recursive one. If you do the recursive call, you do not need the loop, and vice versa.
You can either do it recursively:
def sum_digit(n):
if n > 0:
return sum_digit(n // 10) + n % 10
else:
return 0
Or in an iterative way:
def sum_digit(n):
s = 0
while n > 0:
s += n % 10
n //= 10
return s
Or just using bultin functions (probably not what your teacher wants to see):
def sum_digit(n):
return sum(map(int, str(n)))
i must change the while with a if, and it works,thanks for your comments and sorry for posting such a question here.
This will do the trick:
def sum_digit(n, current_sum=0):
if n == 0:
return current_sum
else:
digit = n % 10
current_sum += digit
n //= 10
return sum_digit(n, current_sum)
The output:
print(sum_digit(67154))
> 23
You were mixing up an iterative method (the while loop) and the recursive method (the function call).
In a recursive function, must make sure you get these things right:
The end condition (in our case, we return the sum when the digit is 0)
and
The recursive call (in our case, going down one digit each time)
Change your code as following:
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
if n > 0 :
sum = sum + sum_digit(n)
return sum
The reason is n is assigned new reference inside function, but it's invisible outside. so while part is loop died. In fact, while part is executed at most once, so code was changed as above.

Using Fibonacci Program to Sum Even Elements

I am trying to solve the following using Python:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
So far, I have been able to generate the Fibonacci elements but in trying to sum the even elements, my code seems to stall. Here is the code below:
def fib(n):
if n==0:
return 0
elif n==1:
return 1
if n>1:
return fib(n-1)+fib(n-2)
n=0
total=0
while fib(n)<=4000000:
if fib(n)%2==0:
total+=fib(n)
print(total)
Any suggestions would be welcome.
You have an infinite loop as n isn't ever incremented up from zero in your while loop. Additionally, why not sum your Fibonacci total as well as find the next Fibonacci value in the same while loop, like this:
x= 1
y=1
total = 0
while x <= 4000000:
if x % 2 == 0:
total += x
x, y = y, x + y
print (total)
Outputs:
4613732
since this looks like a homework assignment, I threw in some interesting Python
from math import sqrt
# Using Binet's formula
def fib(n):
return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
def sum_even_terms(limit = 4000000):
n = total = 0
while True:
term = fib(n)
n += 1
if term > limit: break
if term % 2 == 0:
total += term
return total
print sum_even_terms()
def is_nth_term_even(n):
return (fib(n) % 2 == 0)
print is_nth_term_even(30)
Just for fun, here's a really short solution:
def fib_even_sum(limit=4*10**6):
"""Sum of the even Fibonacci numbers up to the given limit."""
b, c = 1, 2
while c <= limit:
a = b + c; b = c + a; c = a + b
return b // 2
print fib_even_sum() # outputs 4613732
It's based on the following facts:
Every third Fibonacci number is even.
If Fib(n) is even, then the sum of the even Fibonacci numbers up to Fib(n) is equal to the sum of the odd Fibonacci numbers up to Fib(n) (because each even Fibonacci number is the sum of the two preceding odd Fibonacci numbers).
The sum of all Fibonacci numbers (even and odd) up to and including Fib(n) is Fib(n+2) - 1 (via an easy proof by induction).
So if Fib(n) is the last even number to be included in the sum, then
the total you want is just (Fib(n+2) - 1) / 2.
You can also use a generator and add the numbers
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
f = fib()
total = 0
while total <= 4000000:
current = f.next()
if current % 2 == 0:
total += current
print total

Categories

Resources