Project Euler #6: Sum square difference

  • + 0 comments

    Here is a brief introspection on what the issue could be:

    Let's say you have a variable c of type long long and variables a and b of type int. Now, if you type:

    c = a*b
    

    The expression on the RHS is evaluated first with type int, and then the result of that is casted to long long. But this is far too late, as the overflow with ints has already occured (if any), and then the overflowed answer is converted to long long. Instead, what you probably meant to be doing is:

    c = static_cast<long long>(a)*static_cast<long long>(b)
    

    As a side note, this is probably a pain to type in a longer expression, and therefore it is better to just declare N as long long initially, thus ensuring all arithmetic expressions are evaluated as long long.