博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Project Euler 1】Multiples of 3 and 5
阅读量:7218 次
发布时间:2019-06-29

本文共 1084 字,大约阅读时间需要 3 分钟。

题目要求是:

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     }
方法二

 

转载于:https://www.cnblogs.com/zwffff/p/5001443.html

你可能感兴趣的文章
Linux 系统下双机HA的实现
查看>>
02_swarm mode key concepts
查看>>
Eclipse打包插件Fat Jar 解压打包
查看>>
Apache Shiro 使用手册
查看>>
CentOS mini 6.5 安装DB2 Express-C 问题处理记录
查看>>
DirectByteBuffer
查看>>
Docker Compose文件详解 V2
查看>>
Memcached的原理与应用(未完)
查看>>
基于 Confluence 6 数据中心的 SAML 单点登录设置你的身份提供者
查看>>
mysql总结
查看>>
Navicat for MySQL版本更新至v11.2.12,修复多项问题|附下载
查看>>
整理 JAVA中的IO流 (字符流和字节流两个大类)
查看>>
uefi与win8 (根据网络资料整理)
查看>>
Eclipse优化
查看>>
Log4j tutorial with Tomcat examples
查看>>
Kong 网关
查看>>
三层结构视频中的DBHelper.cs
查看>>
[转载] 信息系统项目管理师视频教程——18 项目沟通管理
查看>>
在Windows下建立QT开发环境
查看>>
Jedis、JedisPool、ShardedJedis和ShardedJedisPool,java对redis的基本操作
查看>>