Project Euler: Problem 1 (Possible refactorings and run time optimizations)

前端 未结 13 2041
半阙折子戏
半阙折子戏 2020-12-11 08:35

I have been hearing a lot about Project Euler so I thought I solve one of the problems in C#. The problem as stated on the website is as follows:

If w

13条回答
  •  独厮守ぢ
    2020-12-11 09:13

    Refactoring @mbeckish's very clever solution:

    public int eulerProblem(int max) {
        int t1 = f(max, 3);
        int t2 = f(max, 5);
        int t3 = f(max, 3 * 5);
        return t1 + t2 - t3;
    }
    
    private int f(int max, int n) {
        int a = (max - 1) / n;
        return n * a * (a + 1) / 2;
    }
    

提交回复
热议问题