尤拉計劃001--3或5的倍數
阿新 • • 發佈:2021-09-19
001尤拉計劃001--3或5的倍數
首先,展示一下題目。
Multiples of 3 and 5
If we list all the natural numbers below \(10\) that are multiples of \(3\) or \(5\) , we get \(3\),\(5\) ,\(6\) and \(9\). The sum of these multiples is \(23\).
Find the sum of all the multiples of \(3\) or \(5\) below \(1000\).
\(3\)或\(5\)的倍數
在小於\(10\)的自然數中,\(3\)
求小於\(1000\)的自然數中所有\(3\)或\(5\)的倍數之和。
第一題很簡單,我們需要計算3或5的倍數,需要注意的是,if(i%3==0||i%5==0)
,我們用i%3
,i%5
來判斷它是否為3和5的係數,考慮到題目中所說的是3或5的係數,那麼我們只需要將條件改寫成if(i%3==0||i%5==0)
即可。這道題目我們用暴力迴圈即可解決。
#include <iostream> using namespace std; //暴力迴圈 int main(){ int sum=0; for(int i = 1;i<1000;i++){ if(i%3==0||i%5==0){ sum = sum+i; } } cout<<sum<<endl; return 0; }
最後算出來的結果是233168。