Related
I need to create a program that takes user input n and the finds the first n numbers that aren't divisible by any other prime numbers except 2, 3, and 5. This is what I've got so far:
def is_divisible(i):
for k in range(7, i):
if is_prime(k) == 1 and i % k == 0:
return 1
else:
return 0
def is_prime(k):
for j in range(2, k):
if k % j == 0:
return 0
else:
return 1
while True:
while True:
while True:
try:
n = input("How many numbers do you want to find: ")
n = n.replace(" ", "")
n = int(n)
break
except:
print("Input only natural numbers")
continue
if n == 0:
print("Input only natural numbers")
continue
else:
break
count = 0
i = 0
while count < n:
if i % 2 == 0 and i % 3 == 0 and i % 5 == 0 and is_divisible(i) == 0:
print(i)
count += 1
i += 1
else:
i += 1
repeat = input("To repeat press (1), to end press anything else: ")
if str(repeat) == "1":
continue
else:
print("Bye!")
break
If asked to find 10 numbers the program outputs:
30
60
90
120
150
180
240
270
300
330
The program didn't print 210 (which is divisible by 7) so the algorithm seems, at least, partly correct, but 330 is printed (which is divisible by 11) and I can't figure out why. If I manually change i to 330 and k to 11, the is_prime function correctly finds that 11 is a prime number, but the is_divisible function still returns 0. I can't figure out what's wrong. Any help will be greatly appreciated!
Thanks!
First, you need to fix your is_prime like #Barmar mentions above
Note, this can be optimized in multiple ways, the simplest of which is to only check for j in range(2, int(math.sqrt(k))+1) because a number k won't have any prime factors greater than sqrt(k). Also, we can memorize all the prime numbers found so far, so that if the same number is checked multiple times, subsequent checks are much faster. You can use better algorithms to check if a number is prime, but this should suffice for our purposes.
import math
# A set to remember prime numbers
primes = set()
def is_prime(k):
if k == 1: return False # 1 is not prime
if k in primes: return True # Check remembered prime numbers
# Check all numbers in the closed interval [2, sqrt(k)]
for j in range(2, int(math.sqrt(k))+1):
if k % j == 0:
return False
# Prime number, so remember it
primes.add(k)
return True
The first n numbers that aren't divisible by any prime numbers other than 2, 3, and 5
Since your number needs to be divisible by 2, 3, and 5, you don't need to look at all numbers as you do currently. Just look at multiples of 2 * 3 * 5, i.e. multiples of 30, since those are the only numbers that are going to be multiples of 2, 3, and 5.
So now your problem becomes: "Print 30 * i, where i is not a multiple of a prime number other than 2, 3, and 5. i.e., you need to get the prime factors of i, and check that this set contains only 2, 3, and 5.
There are a number of ways to get the prime factors of a number. Here's a simple one:
def prime_factors(k):
# If k is prime, it is its only prime factor
if is_prime(k):
return {k}
factors = set()
# If divisible by 2, add 2 as a prime factor
if k % 2 == 0:
factors.add(2)
# Check all odd numbers in the closed interval [3, k//2]
for i in range(3, k//2+1, 2):
if k % i == 0 and is_prime(i):
factors.add(i)
return factors
Now that we've defined our helper functions, we just need to call them:
n = 10
i = 1
count = 0
while count < n:
factors = prime_factors(i)
# If we remove {2, 3, 5} from factors, do we get an empty set?
if not factors.difference({2, 3, 5}):
print(2 * 3 * 5 * i)
count += 1
i += 1
Which prints:
30
60
90
120
150
180
240
270
300
360
If you are indeed looking for regular numbers as #Mark and #Kelly suggest in their comments, then you simply skip the multiplication by 2 * 3 * 5:
n = 10
i = 1
count = 0
while count < n:
factors = prime_factors(i)
# If we remove {2, 3, 5} from factors, do we get an empty set?
if not factors.difference({2, 3, 5}):
print(i)
count += 1
i += 1
gives:
1
2
3
4
5
6
8
9
10
12
Here's a bit of code that looks for values that have other factors besides 2,3,5. If there are other factors in there, they must be other prime values because we remove the prime factors 2,3,5 from the number.
primes = [ 2, 3, 5]
count = 10
answers = []
value = 2
while len(answers) < count:
test_value = value
for prime in primes:
while test_value % prime == 0:
test_value //= prime
if test_value == 1:
answers.append(value)
value += 1
print(answers)
Ok, the performance discussion from #Kelly Bundy bothered me - so I added a different approach - but it's got problems.
import sys
primes = [ 2, 3, 5]
count = int(sys.argv[1])
base = round( count ** (1./3.) )
powers = [0] * len(primes)
answers = []
while True:
value = 1
for n in range(len(primes)):
value *= primes[n] ** powers[n]
answers.append(value)
for n in range(len(powers)):
powers[n] += 1
if powers[n] != base:
break
powers[n] = 0
else:
break
for x in sorted(answers):
print(x)
Basically, all of the numbers we want to find are of the form: 2**x * 3**y * 5**z . And so, if we just vary x,y,and z, we can compute all of the qualifying numbers.
The the problem boils down to, which values of x,y, and z are valid. To be honest, I haven't figured that out. All I do is come up with count combinations of x,y,z where I just count values (using some base counting system). For instance, if I need to come up with 1,000 combinations, I just produce all of the combinations of x,y,z where the values are between 0 and 9. And so i get the values (000 - 999). And this produces the values: 2**0 * 3**0 * 5**0 all the way up to 2**9 * 3**9 * 5**9. Now, I'm definitely missing some values. The 1,000 numbers I come up with are NOT the first 1,000 numbers.
Your is_divisible method basically only checks 7 and then returns either 1 or 0.
You want to check all the numbers in the range.
def is_divisible(i):
for k in range(7, i):
if is_prime(k) == 1 and i % k == 0:
return 1
return 0
Your is_prime method suffers from this issue as well:
def is_prime(k):
for j in range(2, k):
if k % j == 0:
return 0
return 1
Fixing these issues, however, is going make this algorithm EXTREMELY slow so you will need to consider some strategies that will make it faster.
Caching the numbers that you have already checked for primeness would be a start.
My program is supposed to find the first m twin primes and print that they are.
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def findTwinPrimes(a , b):
if isItPrime(a) == True:
if isItPrime(b) == True:
if b - a == 2:
print(a, "-", b, "is a twin prime")
def firstMTwinPrimes(m):
o = 0
i = 1
if o < m :
print(i)
k = 3
l = 5
findTwinPrimes(k,l)
k += 1
l += 1
o += 1
firstMTwinPrimes(7)
Currently, it runs without errors but also does not work. The i is to check how many times the program runs and it only runs once. I do not know why becuase if o is less than m it should run again. Also for 3 and 5, they are twin primes but it doesn't work for them. isItPrime is already implemented to check if a number is prime or not. It returns the answer.
please, post your code with function and error
otherwise, try this:
def printTwinPrime(n):
prime = [True for i in range(n + 2)]
p = 2
while (p * p <= n + 1):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n + 2, p):
prime[i] = False
p += 1
# check twin prime numbers
# display the twin prime numbers
for p in range(2, n-1):
if prime[p] and prime[p + 2]:
print("(",p,",", (p + 2), ")" ,end='')
# driver program
if __name__=='__main__':
# static input
n = 7
# Calling the function
printTwinPrime(n)
As #JayMody notes, your isItPrime() is broken. We can make it work as intended, but the way it relies on being called with increasing arguments, and its use of a global primes list, are problems. (I.e. consider first calling isItPrime(22) followed by isItPrime(6))
#JohanC's answer, which you accepted, doesn't maintain a global prime list, instead doing more divisions than necessary by testing all numbers from 2 to the number. This is far less efficient than what you were attempting to implement. I think we can salvage your original intent, and not expose a non-general isItPrime() test, by making one function internal to the other:
def firstMTwinPrimes(m):
primes = [2]
def isItPrime(n):
for prime in primes:
if prime * prime > n:
break
if n % prime == 0:
return False
primes.append(n)
return True
number = 3
count = 0
while count < m:
for n in range(number, number + 3, 2):
if n == primes[-1]:
continue
if not isItPrime(n):
break
else: # no break
print(number, "-", number + 2, "are twin primes")
count += 1
number += 2
We have to be careful not to add a prime to the list twice when it's tested as a lower and upper number. You'll find this approach is a couple of orders of magnitude faster than #JohanC's answer when M exceeds a hundred. You were on the right track.
The sieve-based solution #AlokMishra posted is faster still, but it is designed to find all pairs up to some number, not some number of pairs as you specified.
Some remarks:
You need to change your if o < m to a while loop: while o < m. With only the if-test, findTwinPrimes is only called once. You need to call it again and again until you have enough twin primes. Inside that while-loop, you need to increment o only when you really found twin primes. Therefore, findTwinPrimes should return True when it found a twin prime, and False when it didn't. Also, k=3; l=5 should be put before the start of the while-loop, so they can be incremented inside the loop.
Instead of if isItPrime(a) == True: it is better to just write if isItPrime(a):. That has the same effect and is more readable.
You have a variable i that you just give a value of 1 and print, but don't do anything useful with. You can leave it out.
Python code is more readable if you indent with four spaces instead of only 2
Here is the adapted code:
def isItPrime(p):
for i in range(2, p):
if p % i == 0:
return False
return True
def findTwinPrimes(a, b):
if isItPrime(a):
if isItPrime(b):
if b - a == 2:
print(a, "-", b, "is a twin prime")
return True
return False
def firstMTwinPrimes(m):
o = 0
k = 3
l = 5
while o < m:
if findTwinPrimes(k, l):
o += 1
k += 1
l += 1
firstMTwinPrimes(7)
Output:
3 - 5 is a twin prime
5 - 7 is a twin prime
11 - 13 is a twin prime
17 - 19 is a twin prime
29 - 31 is a twin prime
41 - 43 is a twin prime
59 - 61 is a twin prime
PS: If you want, you can write
if isItPrime(a):
if isItPrime(b):
if b - a == 2:
as
if isItPrime(a) and isItPrime(b) and b - a == 2:
I tried to solve Project Euler #37:
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
I wrote my code in Python but I am facing weird issues.
Here's my code:
def isPrime(n):
if n == 2 or n == 3 or n == 5: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
if n%5 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
def gen(nb):
results = []
nb_str = str(nb)
for k in range(0, len(nb_str) - 1):
results.append(nb_str[k:])
results.append(nb_str[-k:])
return results
def check(nb):
for t in gen(nb):
if not isPrime(int(t)):
return False
return True
c = 0
s = 0
i = 2
while c != 11:
if check(i):
c += 1
s += i
i += 1
print(s)
Where does the error come from? (The expected result is 748317)
I suspect the errors coming from the results list
Yes, the gen() function is not working correctly as your slicing is off, also, you count 2, 3, 5 and 7 as truncatable primes which the question denies.
The second slice should be the other way around:
>>> s = 'abcd'
>>> for i in range(1,len(s)-1):
... print(s[i:])
... print(s[:-i])
...
bcd
abc
cd
ab
which we can see produces the right strings.
Altogether then, the function should be:
def gen(nb):
results = [nb]
nb_str = str(nb)
for k in range(1, len(nb_str)):
results.append(int(nb_str[k:]))
results.append(int(nb_str[:-k]))
return results
note I also added a string to int conversion - not sure how Python didn't make that obvious for you :/
And before get the full solution, Project Euler nearly always gives you an example which you can use to check your code:
>>> check(3797)
True
You must also add a condition in the check function to return False if the number is 2, 3, 5 or 7 as this is stated clearly in the question.
And the result is the expected: 748317.
Joe Iddon has explained the error in your code, but you can speed it up a little by turning gen into an actual generator. That way, you can stop checking the results for a given nb as soon as you detect a composite number (and gen will stop generating them). I've also made a few minor tweaks to your primality tester. Remember, the or operator short-circuits, so if a is True-ish in a or b then it doesn't bother evaluating b.
def isPrime(n):
if n in {2, 3, 5, 7}:
return True
if n < 2 or n%2 == 0:
return False
if n%3 == 0 or n%5 == 0:
return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0 or n%(f+2) == 0:
return False
f += 6
return True
def gen(nb):
yield nb
nb_str = str(nb)
for k in range(1, len(nb_str)):
yield int(nb_str[k:])
yield int(nb_str[:-k])
def check(nb):
for t in gen(nb):
if not isPrime(t):
return False
return True
c = s = 0
# Don't check single digit primes
i = 11
while c < 11:
if check(i):
c += 1
s += i
print(i)
i += 2
print('sum', s)
output
23
37
53
73
313
317
373
797
3137
3797
739397
sum 748317
In fact, you can get rid of the check function, and replace it with all, which also short-circuits, like or does. So you can replace the
if check(i):
with
if all(map(isPrime, gen(i))):
So I had to make a code which generates the first triangle number which has over 500 factors. The problem is given in detail below:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
I have written a block of code which generates the same however it is highly inefficient; kindly suggest some ways to improve it. Moreover it is so inefficient that it only works with numbers below 70
My code is given below, please refer:
def generates_triangle_numbers_upto_n(n):
list = [1]
while len(list)<n:
nth = int(len(list)+1)
to_be_appended = nth/2 + nth**2/2
list.append(to_be_appended)
return list
def return_number_of_n(n):
num = 0
for i in range(2, int(n)):
if n%i == 0:
num = num+1
return num + 2
def main(n):
list = generates_triangle_numbers_upto_n(20000)
for i in list:
if return_number_of_n(i) > int(n):
return i
print(main(100))
I saw a similar question on this site but I didn't understand how it worked:
Thanks a lot!
Edit 1: Thanks everyone for the wonderful suggestions, based on which I have refined my code:
def main(n):
list = [1]
while return_number_of_n_second(list[len(list)-1]) <= n:
nth = int(len(list)+1)
to_be_appended = int(nth/2 + nth**2/2)
list.append(to_be_appended)
return list[len(list)-1]
def return_number_of_n_second(n):
num = 0
import math
sqrt = math.sqrt(n)
for i in range(2, math.ceil(math.sqrt(n))):
if n%i == 0:
num = num+1
if int(sqrt) == sqrt:
return num*2 +3
return num*2 + 2
print(main(500))
However, now too, it takes 10-15 seconds to execute. Is there a way to make it even more efficient since almost all of project euler's problems are to be executed in 2-3 seconds max?
Just some basic technical optimizations and it should do it:
import time
import math
def main(n):
last, length = 1, 1
while return_number_of_n_second(last) <= n:
length += 1
last = int(length/2 * (length+1))
return last
def return_number_of_n_second(n):
sqrt = math.sqrt(n)
if int(sqrt) == sqrt:
return 2
return sum(1 for i in range(2, math.ceil(sqrt)) if not n % i) * 2 + 2
start_time = time.time()
print(main(500))
print(time.time() - start_time)
#!/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);