Java中的Euler程序 [英] Euler program in Java

查看:98
本文介绍了Java中的Euler程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始解决Project Eulers问题。尽管这个很简单。我想就最佳解决方案发表看法。

I just started with solving Project Eulers problems. Even though this one is very simple. I want to take your opinion on the best solution.

问题


如果我们列出低于10的所有自然数
是3或5的倍数,
我们得到3,5,6和9.这些
倍数的总和是23.

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.

查找所有3
或5以下的倍数的总和。

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

这就是我编码的方式:

package com.problem.one.ten;
public class NaturalNumber {

    public static void main(String args[])  {
        int sum=0;
        for(int i=0; i<1000; i++) {
            if((i%3 == 0) || (i%5 == 0)){
                sum += i;
            }
        }
        System.out.println(sum);
    }
}


推荐答案

它看起来不错,不过我会在main中加上 sum 。这个简单的程序并不是什么大不了的事。但一般来说,你应该在尽可能窄的范围内声明变量。

It looks fine, though I would put sum in main. It's not a big deal on such a simple program. But in general, you should declare variables in the narrowest possible scope.

这篇关于Java中的Euler程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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