歐拉計劃 第1題

題目

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.

找出1000以下自然數中3和5的倍數之和。

10以下的自然數中,屬於3和5的倍數的有3,5,6和9,它們之和是23.

找出1000以下的自然數中,屬於3和5的倍數的數字之和。

解答:這題比較循環遍歷就可以了。

程序

public class N_1 {
	public static void main(String[] args)
	{
		int i,sum=0;
		for(i=1;i<1000;i++)
		{
			if(i%15==0)
				sum = sum+i;
			else if(i%3==0)
				sum = sum+i;
			else if(i%5==0)
				sum = sum+i;
		}
		System.out.println("sum:"+sum);
	}
}

運行結果:sum:233168
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章