Java 中 10,000 以下的 3、5 或 7 倍数的总和 [英] Sum of numbers under 10,000 that are multiples of 3, 5 or 7 in Java

查看:27
本文介绍了Java 中 10,000 以下的 3、5 或 7 倍数的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何让程序将 3、5 和 7 的倍数之和相加,但我不确定如何让程序只使用每个数字一次.例如,我可以让程序找出所有数字并将它们相加为 3,然后对 5 执行相同的操作,但是数字 15 将在最终数字中出现两次.我不确定我是如何让它只取一次号码的.感谢您的帮助.

I know how to get the program to add up the sums of the multiple for each of 3, 5 and 7, but I'm not sure how I'd get the program to only use each number once. For example, I can get the program to find out all of the numbers and add them up for 3 and then do the same for 5, but then the number 15 would be in the final number twice. I'm not sure exactly how I'd get it to only take the number once. Thanks for any help.

推荐答案

最简单的方法是使用 for 循环,因此:

The easiest approach would be to use a for loop thus:

int sum = 0;
for(int i=1; i<10000; i++)
{
    if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0)
        sum += i;
}

这篇关于Java 中 10,000 以下的 3、5 或 7 倍数的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆