EvilZone
Programming and Scripting => Beginner's Corner => : AnonymousCelt March 22, 2015, 10:24:27 PM
-
Task is to return the sum of all even fibonacci numbers below 4000000.
def ProblemTwo():
last = 1
current = 1
temp = 2
tally = 0
while current < 4000000:
temp = last + current
last = current
current = temp
if current % 2 == 0:
tally += current
print "My Answer is: %d" % tally
def main():
ProblemTwo()
if __name__ == '__main__':
main()
Any feedback is greatly appreciated.
-
Not wrong perse but why do you use a while and not a for loop ?
-
Not wrong perse but why do you use a while and not a for loop ?
To be honest, because I was causing iteration within the loop and the variable was already defined I thought it would be best using the while loop as it only needs the check added.
Might be different in Python though (came from Java).
-
Well tell you what you should really read about the numbers before coding it out. Bruteforcing isn't a good practice. You should carefully observe the stuff.
I will give you a simple hint with which you can improve your code.
Lets examine the Fibo series :-
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, .....
Do you observe something ?
What we observe is that every third number is even.
Well that's your hint for now.
-
Well tell you what you should really read about the numbers before coding it out. Bruteforcing isn't a good practice. You should carefully observe the stuff.
I will give you a simple hint with which you can improve your code.
Lets examine the Fibo series :-
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, .....
Do you observe something ?
What we observe is that every third number is even.
Well that's your hint for now.
Ah, I get it.
For loop incrementing the fib sequence by 3 at a time, adding to the tally/total avoiding the need to verify whether it is even or not.
I posted this before receiving your feedback in the first project euler question. I'll look back into it all for a while before doing any more as I clearly have more to learn before I can benefit fully from the exercises.
-
Alright. I will try to post some detailed answer on this. Maybe tomorrow.