【Project Euler 1】Multiples of 3 and 5

題目要求是:ide

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.spa

Find the sum of all the multiples of 3 or 5 below 1000.code

這個題目提供兩種方法來計算。blog

方法一:採用最笨拙的方式,直接從1到1000,每個數都去看看是否能夠被3或者5整除。Java實現代碼以下:ip

1 public static long getSum(int number) {
2         long sum = 0;
3         for (int i = 1; i < number; i++) {
4             if (i % 3 == 0 || i % 5 == 0) {
5                 sum += i;
6             }
7         }
8         return sum;
9     }
方法一

方法二:利用求和公式,咱們知道1000以內被3整數的最大數,應該是999/3=333,因此全部能夠被3整除的數的總和應該是3*(1+2+...+333)=3*(333+334)/2 { 求和公式爲:1+2+...+n=n*(n+1)/2 },同理,全部能夠被5整數的數的總和是5*(1+2+...+199)=5*(199+200)/2,可是這裏還有一個問題,就是那些既能被3,又能被5整除的數(也就是能被15整除的數),被計算了兩次,所以須要再減去一次全部能被15整除的數。Java實現代碼以下:get

1 public static long getSumBetter(int number){
2         /* (1+2+...+333)*3+(1+2+...+199)*5-(1+2+..+66)*15 */
3         int num = number - 1;
4         return  ((num / 3) * (num / 3 + 1) * 3) / 2 + ((num / 5) * (num / 5 + 1) * 5) / 2 - ((num / 15) * (num / 15 + 1) * 15 / 2);
5     }
方法二
相關文章
相關標籤/搜索