zoukankan      html  css  js  c++  java
  • 【Project Euler 1】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.

    这个题目提供两种方法来计算。

    方法一:采用最笨拙的方式,直接从1到1000,每一个数都去看看是否可以被3或者5整除。Java实现代码如下:

    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实现代码如下:

    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     }
    方法二
  • 相关阅读:
    【类的继承与派生】学习笔记
    c++类的学习笔记
    c++链表
    实验六--类和对象
    mission3--dp
    POJ2718Smallest Difference(暴力全排列)
    我也不知道该起什么标题....
    noip2014题解
    Windows平台整合SpringBoot+KAFKA__第2部分_代码编写前传
    Windows平台整合SpringBoot+KAFKA_第1部分_环境配置部分
  • 原文地址:https://www.cnblogs.com/zwffff/p/5001443.html
Copyright © 2011-2022 走看看