相关疑难解决方法(0)

Java中的项目Euler#1

我遇到了这段代码的问题.我不想看别人,所以我想知道我的错是什么.

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

求出1000以下3或5的所有倍数的总和.

public class Multiples {
    public static void main (String [] args) {
        int temp = 0;
        int temp2 = 0; 

        for (int i = 0; i <= 1000; i++) {
            if (i % 3 == 0) {
                temp = temp + i;
            }            
        }

        for (int j = 0; j <= 1000; j++) {
            if (j % 5 == 0) {
                temp2 = temp2 + j;
            }
        }

        System.out.println(temp + temp2);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的值是267333,这是错误的.我的添加错了吗?我在算法上知道,这段代码可能达不到标准,但它应该有用,对吧?

java

6
推荐指数
2
解决办法
9191
查看次数

项目Euler:问题1(可能的重构和运行时优化)

我听过很多关于Project Euler的消息,所以我想我解决了C#中的一个问题.网站上所述的问题如下:

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

求出1000以下3或5的所有倍数的总和.

我编写了如下代码:

  class EulerProblem1
    {
        public static void Main()
        {
            var totalNum = 1000;
            var counter = 1;
            var sum = 0;

            while (counter < totalNum)
            {
                if (DivisibleByThreeOrFive(counter))
                    sum += counter;

                counter++;
            }

            Console.WriteLine("Total Sum: {0}", sum);
            Console.ReadKey();
        }

        private static bool DivisibleByThreeOrFive(int counter)
        {
            return ((counter % 3 == 0) || (counter % 5 == 0));

        }
    } 
Run Code Online (Sandbox Code Playgroud)

能够以更少的冗长/更清晰的语法和更好的优化来获得关于替代实现的一些想法将会很棒.这些想法可能从快速和肮脏到带出大炮消灭蚊子.目的是探索计算机科学的深度,同时尝试改进这个特别琐碎的代码片段.

谢谢

c# algorithm optimization refactoring

4
推荐指数
1
解决办法
4005
查看次数

标签 统计

algorithm ×1

c# ×1

java ×1

optimization ×1

refactoring ×1