問題1:3和5的倍數
Published on Friday, 5th October 2001, 06:00 pm;
2001年10月5日 星期五 下午6:00發佈
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,5,6和9。這些數字的總和是23。
找出小於1000的自然數3或5的倍數。
方法一:最簡單的方法爲循環1到1000並判斷是否能整除3或5
1 uint Sum=0; 2 for(uint curNum=1;curNum<1000;curNum++)if(curNum%3==0 || curNum%5==0) 3 Sum+=curNum;
執行次數:999次;
方法二:如果每次分別進行相加,再去減掉公倍數
1 private uint CountNumSum(uint belowNum,uint uIntNum) 2 { 3 uint curSum = 0; 4 for (uint curNum = uIntNum; curNum < belowNum; curNum += uIntNum) 5 { 6 curSum += curNum; 7 } 8 } 9 uint Sum=0; 10 Sum=CountNumSum(1000,3)+CountNumSum(1000,5)-CountNumSum(15);
執行次數:333+199+66=598次
方法三:這個題目其實還有個最簡便的方法,無需循環
1 private uint CountNumSum(uint belowNum,uint uIntNum) 2 { 3 return --belowNum / uIntNum * uIntNum * (1 + belowNum / uIntNum) /2; 4 } 5 uint Sum=0; 6 Sum=CountNumSum(1000,3)+CountNumSum(1000,5)-CountNumSum(1000,15);
毫無疑問,方法三的執行速度是最快的,不存在循環。