2013-07-13 57 views
-1

這個Ruby代碼有什麼問題?我正在努力解決the first Project Euler question如何在Ruby中迭代?

我認爲問題是在sum += num的語法,但我不明白這是什麼適當的語法。

sum = 0 
num = 0 
num2 = 0 

loop do 
    num += 1 
    if num % 3 == 0 
    sum += num 
    break if num > 1000 
    end 
end 

loop do 
    num2 += 1 
    if num2 % 5 == 0 
    sum += num2 
    break if num2 > 1000 
    end 
end 

puts sum 
+1

有沒有你可能計算兩次的數字? –

+1

沒有錯。它是有效的Ruby代碼。 – sawa

回答

3

你使這種方式複雜得多,它需要的。此外,如果該數字是3 5的倍數,則會添加兩次。嘗試是這樣的:

sum = 0 # initialize the sum 
(1...1000).each { |x| # loop from 1 to 1000 
    sum += x if x % 3 == 0 || x % 5 == 0 # add the number to the sum if it is 
             # divisible by 3 or 5 
} 
puts sum # output the sum 
4

這裏有一個選擇:

(1...1000).select { |x| x % 3 == 0 || x % 5 == 0 }.reduce(:+) 
+0

爲什麼你把'&:+'放在'reduce'裏面?我一直用':+'來看它。 – Doorknob

+0

請看這裏:http://blog.thoughtfolder.com/2008-02-25-a-detailed-explanation-of-ruby-s-symbol-to-proc.html。 –

+0

嗯,是的,我知道它做了什麼,但爲什麼不使用':+'代替'&:+'?它更短,更易於理解,並且可以刪除和不必要地調用'to_proc'。 – Doorknob

0

這將運行,你的語法是否正確,而是因爲,如前所述,你加兩個3的倍數沒有給出正確的答案, 5次兩次,一次在第一次循環中,使用num,第二次循環使用num2

所以你有兩個循環,但實際上你只需要一個循環。

您只需要考慮每個數字一次,您可以檢查它是否是3或5的倍數。這將解決您的重複計算問題,並使您的代碼更加簡潔。

此外,與Doorknob顯示的一樣,each語法將爲您節省這些循環中的一些行。你也可以使用for語法:

for num in (1..1000) 
    <stuff here> 
end 

退房種循環的「Loops: How to do thousands of operations with a few lines of code.」。