Sum of factorial digits I have seen one algorithmic task and I am not sure if my solution is fully efficient. As input to the method you are given positive integer N. And you should return the sum of values of the digits in a decimal representation of N!.

For example, given N = 6 the function should return 9, because N != 720 and sum of digits 7 + 2 + 0 = 9. Result cannot exceeds 100000000. N is higher or equal than 1 and less or equal than 2000.

Is this an efficient solution and the best optimized?

public int solution(int N) {
    long factorial = 1;
    for (int i = 1; i &lt;= N; i++)
        factorial = factorial * i;
    long res = 0;

    while(factorial&gt;0) {
        res+=factorial%10;
        factorial/=10;
    }
    if (res &gt; 100000000)
        return -1;
    return (int) res;
}
Your code only works for small values of N. The algorighm is effective, but unfortunately your overflows are real.

Factorial numbers get very big, very fast... I think it is around 12! that you run out of space in a 32-bit integer, and about 20! that your run out of space in a 64-bit long.

You need to convert your logic to use BigInteger instead of Long for it to work at all.