Disclaimer: This question is not specific to roblox scripting, but is for learning lua. Continue to read if you’d still like to help.
There’s a coding problem on this website [link above as well], and here it is:
"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."
Me and my friend have been trying to solve this problem for the 30 minutes - 1 hour, and we finally (thought) we got the solution! But as it turns out, it’s off by 2 digits?? I’m surprised it’d be off by that little. Is there some little thing that we did wrong?
Here’s the code (grandSum is our answer):
local grandSum = 0
local a = 1
local b = 2
local c = 0
local switch = false
while c < 4000000 do
if switch == false then
c = a + b
switch = true
if c % 2 == 0 and c <= 4000000 then
grandSum = grandSum + c
print("C: " .. c)
end
end
if switch == true then
a = b
b = c
c = a + b
if c % 2 == 0 and c <= 4000000 then
grandSum = grandSum + c
print("C: " .. c)
print("grandSum: " .. grandSum)
end
end
end
So the correct answer it says is 4613732. However, we got 4613730… odd.
I know this isn’t directly roblox related, but since it’s all a part of learning lua/roblox lua, I thought I could post here.
Thanks!