Euler Project No. 2 with Python - python

Can somebody tell me why this should be wrong?
#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, ...
#Find the sum of all the even-valued terms in the sequence
#which do not exceed four million.
sum=2
list = [1,2]
for x in range(2,100):
a = list[x-2]+list[x-1]
print(a)
list.append(a)
if a % 2 == 0:
sum += a
print('sum', sum)
if sum >= 4000000:
break

Here's a completely different way to solve the problem using a generator and itertools:
def fib():
a = b = 1
while 1:
yield a
a, b = b, a + b
import itertools
print sum(n for n in itertools.takewhile(
lambda x: x <= 4000000, fib()) if n % 2 == 0)
Output:
4613732
So your code, even though it is wrong (see other answers), happens to give the correct answer.

replace
sum += a
print('sum', sum)
if sum >= 4000000:
break
with
if a > 4000000:
break
sum += a
print('sum', sum)
You should compare "a" with 4000000, not "sum", like Daniel Roseman said.

The question asked for the sum of even terms which do not exceed four million. You're checking if the sum doesn't exceed 4m.

I'm trying to solve the same problem - although I understand the logic to do it, I don't understand why this works (outputs the right sum)
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
l.append(n)
print n
And then then moment I put in the modulo function, it doesn't output anything at all anymore.
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
if n % 2 == 0 :
l.append(n)
print n
I'm sure this is fairly simple...thanks!

This is the code I used. It is very helpful and teaches you about generators.
def fib():
x,y = 0,1
while True:
yield x
x,y = y, x+y
def even(seq):
for number in seq:
if not number % 2:
yield number
def under_a_million(seq):
for number in seq:
if number > 4000000:
break
yield number
print sum(even(under_a_million(fib())))
-M1K3

Keep it simple and it should take you less than 0.1 seconds.
from datetime import datetime
x, y = 1, 1
total = 0
for i in xrange (1, 100):
x = x + y
if x % 2 == 0 and x <= 4000000:
total += x
y = y + x
if y % 2 == 0 and x <= 4000000:
total += y
print total
starttime = datetime.now()
print datetime.now() - starttime

Related

Adding all even fibonacci numbers

I am trying to add all even Fibonacci numbers up to 4000000. I have successfully outputted all Fibonacci numbers up to 4000000, but adding all the even ones is becoming a problem for me. So far this is what I tried:
fibonacci = [1, 2]
i = 0
while fibonacci[-1] < 4000000:
fib = fibonacci[-1] + fibonacci[-2]
fibonacci.append(fib)
i += 1
del fibonacci[-1]
result = 0
for x in fibonacci:
if fibonacci[x] % 2 == 0:
result += fibonacci[x]
print(result)
It outputs an error:
IndexError: list index out of range
In the lines:
for x in fibonacci:
if fibonacci[x] % 2 == 0:
result += fibonacci[x]
x is actually the Fibonacci number itself, not an index, and is guaranteed to be outside of the bounds of the fibonacci list. If the code was for x in range(len(fibonacci)):, this would yield the indexes as x.
Change it to:
for x in fibonacci:
if x % 2 == 0:
result += x
or better yet, use a list comprehension:
result = sum(x for x in fibonacci if x % 2 == 0)
print(result)
Furthermore, instead of building an entire list, you could accumulate the sum on the spot as you generate the Fibonacci numbers, which is much more memory-efficient:
def even_fib_sum(n):
total = 0
a = 0
b = 1
while a < n:
if a % 2 == 0:
total += a
a, b = a + b, a
return total
if __name__ == "__main__":
print(even_fib_sum(55))
Or, even better, you can use a generator and drop even, since fib is more generally reusable:
def fib(n):
a = 0
b = 1
while a < n:
yield a
a, b = a + b, a
if __name__ == "__main__":
print(sum(x for x in fib(4000000) if x % 2 == 0))
Note that the Fibonacci series usually begins with 0, 1, 1, 2, 3, 5... rather than 1, 2, 3, 5... but you can adjust this as necessary, along with whether you want to iterate inclusive of n or not.
A small compilation of previous answers
fibonacci = [0, 1]
while fibonacci[-1] + fibonacci[-2] < 4000000:
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print(sum(x for x in fibonacci if x % 2 == 0))
That's how I wrote as a beginner.
#By considering the terms in the Fibonacci sequence whose values do
#not exceed four million,
#find the sum of the even-valued terms.
cache = {}
def fib(n):
if n < 3:
return 1
elif n in cache:
return cache[n]
else:
value = fib(n - 1) + fib(n - 2)
cache[n] = value
return value
tot = 0
for n in range(1, 34):
if fib(n) % 2 == 0:
tot += fib(n)
print(n, ':', fib(n))
print(tot)

Count how many individual integers there are in a string, Python 3

What I need is to show how many integers that are less than N that are not dividable by 2,3 or 5. I have managed to get the list of numbers that are less than N and are not divisible by 2,3 or 5 but I cannot for the life of me get Python to actually count how many integers there are.
What I have so far is
N = int(input("\nPlease input a Number "))
if N < 0:
print("\nThere are no answers")
else:
for a in range(1,N+1,2):
if a%3 !=0:
if a%5 !=0:
Try this:
N = 20
counter = 0
for a in range(1, N):
if a%2 and a%3 and a%5:
counter += 1
The result will be in counter at the end of the loop. Or for a fancier version, adapted from #iCodez's answer:
sum(1 for x in range(1, N) if all((x%2, x%3, x%5)))
=> 6
Have you tried declaring a global variable and incrementing it?
i = 0
... if a % 5 != 0:
i += 1
print i
This can be done quite easily using a list comprehension, all, and len:
>>> num = int(input(':'))
:20
>>> [x for x in range(num) if all((x%2, x%3, x%5))]
[1, 7, 11, 13, 17, 19]
>>> len([x for x in range(num) if all((x%2, x%3, x%5))])
6
>>>

Fibonacci list how do i make a conditional that excludes a number

fib = [0,1]
a = 1
b = 0
i = 0
while i < n:
i = a+b
a,b = i, a
fib.append(i)
This works in cases where 'n' (which is a given variable) is a number in an actual Fibonacci sequence, like 21 or 13. However, if the number is something like six, it adds one more number than it should. The list should not contain a number that is greater than n.
You could always add a to the list first, then do your incrementing.
fib = [0]
a, b = 1, 0
while a <= n:
fib.append(a)
a,b = a+b, a
Using the classic shnazzy recursive Fibonacci function (which took me a few tries to remember and get right):
def fib(num):
if ((num == 0) or (num == 1)): return 1
fib_num = fib(num - 1) + fib(num - 2)
return fib_num
x, n, i = 2, 15, []
while (fib(x) < n):
i.append(fib(x))
x += 1

Collatz conjecture sequence

The Collatz conjecture
what i am trying to do:
Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].
background on collatz conjecture:
Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
What I have so far:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x= x/2
else:
x= 3*x+1
return seq
When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.
You forgot to append the x values to the seq list:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
seq.append(x) # Added line
return seq
Verification:
~/tmp$ python collatz.py
[6, 3, 10, 5, 16, 8, 4, 2, 1]
def collatz_sequence(x):
seq = [x]
while seq[-1] > 1:
if x % 2 == 0:
seq.append(x/2)
else:
seq.append(3*x+1)
x = seq[-1]
return seq
Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.
>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)
Here's another way of doing it:
while True:
x=int(input('ENTER NO.:'))
print ('----------------')
while x>0:
if x%2==0:
x = x/2
elif x>1:
x = 3*x + 1
else:
break
print (x)
This will ask the user for a number again and again to be put in it until he quits
def collatz(x):
while x !=1:
print(int(x))
if x%2 == 0:
x = x/2
else:
x = 3*x+1
this is what i propose..
seq = []
x = (int(input("Add number:")))
if (x != 1):
print ("Number can't be 1")
while x > 1:
if x % 2 == 0:
x=x/2
else:
x = 3 * x + 1
seq.append (x)
print seq
This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.
collatz = []
def collatz_sequence(x):
while x != 1:
if x % 2 == 0:
x /= 2
else:
x = (3*x + 1)/2
collatz.append(int(x))
print(collatz)
collatz_sequence()
Recursion:
def collatz(n):
if n == 1: return [n]
elif n % 2 == 0: return [n] + collatz(int(n/2))
else: return [n] + collatz(n*3+1)
print(collatz(27))
steps=0
c0 = int(input("enter the value of c0="))
while c0>1:
if c0 % 2 ==0 :
c0 = c0/2
print(int(c0))
steps +=1
else:
c0 = (3 * c0) + 1
print(int(c0))
steps +=1
print("steps= ", steps)
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
def collatz_sequence(N):
seq = [N]
m = 0
maxN = 0
while seq[-1] > 1:
if N % 2 == 0:
k = N//2
seq.append(N//2)
if k > maxN:
maxN = k
else:
k = 3*N+1
seq.append(3*N+1)
if k > maxN:
maxN = k
N = seq[-1]
m = m + 1
print(seq)
x = np.arange(0, m+1)
y = np.array(seq)
xlim(0, m+1)
ylim(0, maxN*1.1)
step(x, y)
show()
def collatz_exec():
print('Enter an Integer')
N = int(input())
collatz_sequence(N)
This is how you can use it:
>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]
And a plot that shows the sequence:
seq = []
def collatz_sequence(x):
global seq
seq.append(x)
if x == 1:
return
if (x % 2) == 0:
collatz_sequence(x / 2)
else:
collatz_sequence((x * 3) + 1)
collatz_sequence(217)
print seq
def collataz(number):
while number > 1:
if number % 2 == 0 :
number = number //2
print(number)
elif number % 2 ==1 :
number = 3 * number + 1
print(number)
if number == 1 :
break
print('enter any number...!')
number=int(input())
collataz(number)

Finding the sum of even valued terms in Fibonacci sequence

#!/usr/bin/python2
"""
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.
"""
odd, even = 0,1
total = 0
while True:
odd = odd + even #Odd
even = odd + even #Even
if even < 4000000:
total += even
else:
break
print total
My algo:
If I take first 2 numbers as 0, 1; the number that I find first in while loop will be an odd number and first of Fibonacci series.
This way I calculate the even number and each time add the value of even to total.
If value of even is greater than 4e6, I break from the infinite loop.
I have tried so much but my answer is always wrong. Googling says the answer should be 4613732 but I always seem to get 5702886
Basically what you're doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.
What you should do instead is just iterate over all the fibonacci values below 4000000 and do a if value % 2 == 0: total += value. The % is the remainder on division operator, if the remainder when dividing by 2 equals 0 then the number is even.
E.g.:
prev, cur = 0, 1
total = 0
while True:
prev, cur = cur, prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)
def fibonacci_iter(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print sum(a for a in fibonacci_iter(4e6) if not (a & 1))
Here is simple solution in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=1,j=1,sum=0;
while(i<4000000)
{
i=i+j;
j=i-j;
if(i%2==0)
sum+=i;
}
printf("Sum is: %d",sum);
}
Your code includes every other term, not the even-valued ones. To see what's going on, print even just before total += even - you'll see odd numbers. What you need to do instead is check the number you're adding to the total for evenness with the modulo operator:
total = 0
x, y = 0, 1
while y < 4000000:
x, y = y, x + y
if x % 2:
continue
total += x
print total
code in python3:
sum = 2
a = 1
b = 2
c = 0
while c <= 4000000:
c = a + b
if c%2 == 0:
sum += c
a,b = b,c
print(sum)
output >>> 4613732
You just misunderstood with the even sequence and even value.
Example: 1, 2, 3, 5, 8, 13, 21
In the above sequence we need to pick 1, 3, 5, 13, 21 and not 2, 5, 13.
Here is the solution fro JAVA
public static void main(String[] args) {
int sum = 2; // Starts with 1, 2: So 2 is added
int n1=1;
int n2=2;
int n=0;
while(n<4000000){
n=n1+n2;
n1=n2;
n2=n;
if(n%2==0){
sum=sum+n;
}
}
System.out.println("Sum: "+sum);
}
Output is,
Sum: 4613732
def fibLessThan(lim):
a ,b = 1,2
total = 0
while b<lim:
if b%2 ==0:
total+=b
a,b = b,a+b
return total
I tried this exactly working answer. Most of us are adding number after fib formula where we are missing 2. With my code I am adding 2 first then fib formula. This is what exact answer for the Euler problem.
This is the second problem in the Project Euler series.
It is proven that every third Fibonacci number is even (originally the zero was not part of the series). So I start with a, b, c being 0,1,1 and the sum will be every recurring first element in my iteration.
The values of my variables will be updated with each being the sum of the preceding two:
a = b + c, b = c + a , c = a + b.
The variable a will be always even. In this way I can avoid the check for parity.
In code:
def euler2():
a, b, c, sum = 0, 1, 1, 0
while True:
print(a, b, c)
a, b, c = (b + c), (2 * c + b), (2 * b + 3 * c)
if a >= 4_000_000:
break
sum += a
return sum
print(euler2())
it should be:
odd, even = 1,0
Also, every third numer is even (even + odd + odd = even).
If you add every second value of the fibonacci sequence you'll get the next fibonacci value after the last added value. For example:
f(0) + f(2) + f(4) = f(5)
0 + 1 + 3 + 8 = 13
But your code currently does not add the first even value 1.
Other answers are correct but note that to just add all even numbers in an array, just do
myarray=[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
sum(map(lambda k:k if k%2 else 0, myarray))
or
sum([k if k%2 else 0 for k in [1,2,3,4,5]])
Every 3rd item in the Fibonnaci sequence is even. So, you could have this:
prev, cur = 0, 1
count = 1
total = 0
while True:
prev, cur = cur, prev + cur
count = count + 1
if cur >= 4000000:
break
if count % 3 == 0:
total += cur
print(total)
or this (changing your code as little as possible):
even, odd = 0,1 # this line was corrected
total = 0
while True:
secondOdd = even + odd # this line was changed
even = odd + secondOdd #Even # this line was changed
if even < 4000000:
total += even
odd = secondOdd + even # this line was added
else:
break
print total
Another way would be (by the use of some simple math) to check that the sum of a2+a5+a8+a11+...+a(3N+2) (the sum of even Fibonacci values) is equal to (a(3N+4)-1)/2. So, if you can calculate directly that number, there is no need to calculate all the previous Fibonacci numbers.
not sure if your question is already answered or you've found a solution, but here's what you're doing wrong. The problem asks you to find even-valued terms, which means that you'll need to find every value in the fibonacci sequence which can be divided by 2 without a remainder. The problem does not ask you to find every even-indexed value. Here's the solution to your problem then, which gives a correct answer:
i = 1
total = 0
t = fib(i)
while t <= 4000000:
t = fib(i)
if t % 2 == 0:
total += t
i += 1
print total
Basically you loop through every each value in fibonacci sequence, checking if value is even by using 'mod' (% operator) to get remainder, and then if it's even you add it to sum.
Here is how I was able to solve this using native javascript.
var sum = 0,
x = 1,
y = 2,
z = 0;
while (z < 4000000) {
if (y%2==0){
sum +=y;
}
z = x + y;
x = y;
y = z;
} console.log(sum);
I did it differently.
def fibLessThan(lim):
#################
# Initial Setup #
#################
fibArray=[1, 1, 2]
i=3
#####################
# While loop begins #
#####################
while True:
tempNum = fibArray[i-2]+fibArray[i-1]
if tempNum <= lim:
fibArray.append(tempNum)
i += 1
else:
break
print fibArray
return fibArray
limit = 4000000
fibList = fibLessThan(limit)
#############
# summation #
#############
evenNum = [x for x in fibList if x%2==0]
evenSum = sum(evenNum)
print "evensum=", evenSum
Here is my Python code:
even_sum = 0
x = [1, 1] # Fibonacci sequence starts with 1,1...
while (x [-2] + x [-1]) < 4000000: # Check if the coming number is smaller than 4 million
if (x [-2] + x [-1]) % 2 == 0: # Check if the number is even
even_sum += (x [-2] + x [-1])
x.append (x [-2] + x [-1]) # Compose the Fibonacci sequence
print (even_sum)
Although it's hard to believe that a question with 17 answers needs yet another, nearly all previous answers have problems in my view: first, they use the modulus operator (%) aka division to solve an addition problem; second, they calculate all the numbers in the sequence and toss the odd ones; finally, many of them look like C programs, using little of Python's advantages.
Since we know that every third number of the Fibonacci sequence is even, we can generate every third number starting from 2 and sum the result:
def generate_even_fibonacci(limit):
previous, current = 0, 2
while current < limit:
yield current
previous, current = current, current * 4 + previous
print(sum(generate_even_fibonacci(4_000_000)))
OUTPUT
> python3 test.py
4613732
>
So much code for such a simple series. It can be easily shown that f(i+3) = f(i-3) + 4*f(i) so you can simply start from 0,2 which are f(0),f(3) and progress directly through the even values striding by 3 as you would for the normal series:
s,a,b = 0,0,2
while a <= 4000000: s,a,b = s+a,b,a+4*b
print(s)
I solved it this way:
list=[1, 2]
total =2
while total< 4000000:
list.append(list[-1]+list[-2])
if list[-1] % 2 ==0:
total += list[-1]
print(total)
long sum = 2;
int start = 1;
int second = 2;
int newValue = 0;
do{
newValue = start + second;
if (newValue % 2 == 0) {
sum += newValue;
}
start = second;
second = newValue;
} while (newValue < 4000000);
System.out.println("Finding the totoal sum of :" + (sum));`enter code here`
The first mistake was you messed the Fibonacci sequence and started with 0 and 1 instead of 1 and 2. The sum should therefore be initialized to 2
#!/usr/bin/python2
firstNum, lastNum = 1, 2
n = 0
sum = 2 # Initialize sum to 2 since 2 is already even
maxRange = input("Enter the final number")
max = int(maxRange)
while n < max:
n = firstNum + lastNum
firstNum = lastNum
lastNum = n
if n % 2 == 0:
sum = sum + n
print(sum)
I did it this way:)
It works completely fine:)
n = int(input())
f = [0, 1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
sum = 0
for i in f:
if i>n:
break
elif i % 2 == 0:
sum += i
print(sum)
There are many great answers here. Nobody's posted a recursive solution so here's one of those in C
#include <stdio.h>
int filt(int n){
return ( n % 2 == 0);
}
int fib_func(int n0, int n1, int acc){
if (n0 + n1 > 4000000)
return acc;
else
return fib_func(n1, n0+n1, acc + filt(n0+n1)*(n0+n1));
}
int main(int argc, char* argv){
printf("%d\n", fib_func(0,1,0));
return 0;
}
This is the python implementation and works perfectly.
from math import pow
sum=0
summation=0
first,second=1,2
summation+=second
print first,second,
while sum < 4*math.pow(10,6):
sum=first+second
first=second
second=sum
#i+=1
if sum > 4*math.pow(10,6):
break
elif sum%2==0:
summation+=sum
print "The final summation is %d" %(summation)
problem in your code basicly related with looping style and checking condition timing. with below algorithm coded in java you can find (second + first) < 4000000 condition check and it brings you correct ( which less than 4000000) result, have a nice coding...
int first = 0, second = 1, pivot = 0;
do {
if ((second + first) < 4000000) { // this is the point which makes your solution correct
pivot = second + first;
first = second;
second = pivot;
System.out.println(pivot);
} else {
break;
}
} while (true);

Categories