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

前端 未结 13 2069
半阙折子戏
半阙折子戏 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:01

    I haven't written any Java in a while, but this should solve it in constant time with little overhead:

    public class EulerProblem1
    {
        private static final int EULER1 = 233168;
        // Equal to the sum of all natural numbers less than 1000
        // which are multiples of 3 or 5, inclusive.
    
        public static void main(String[] args)
        {
            System.out.println(EULER1);
        }
    }
    

    EDIT: Here's a C implementation, if every instruction counts:

    #define STDOUT     1
    #define OUT_LENGTH 8
    
    int main (int argc, char **argv)
    {
        const char out[OUT_LENGTH] = "233168\n";
        write(STDOUT, out, OUT_LENGTH);
    }
    

    Notes:

    • There's no error handling on the call to write. If true robustness is needed, a more sophisticated error handling strategy must be employed. Whether the added complexity is worth greater reliability depends on the needs of the user.
    • If you have memory constraints, you may be able to save a byte by using a straight char array rather than a string terminated by a superfluous null character. In practice, however, out would almost certainly be padded to 8 bytes anyway.
    • Although the declaration of the out variable could be avoided by placing the string inline in the write call, any real compiler willoptimize away the declaration.
    • The write syscall is used in preference to puts or similar to avoid the additional overhead. Theoretically, you could invoke the system call directly, perhaps saving a few cycles, but this would raise significant portability issues. Your mileage may vary regarding whether this is an acceptable tradeoff.

提交回复
热议问题