Search code examples
javaalgorithmfactorial

Trailing Number of Zeros wrong answer on SPOJ (JAVA)


Today I try to solve "Factorial" problem on SPOJ (link) and it looks like easy Trailing Number of Zeros algorithm, but all time I got on SPOJ "Wrong answer".

Algorithm is very easy and works perfect for all tests (from SPOJ, other sources and everything that I created manually), but "Wrong answer" after 0.99 sec...

Here my code:

public static int ZeroCount (int num)
{
    int zeros = 0;
    for (int i =5; i < num; i*=5)
        zeros = zeros + (int)Math.floor(num/i);
    return zeros;
}

public static void main(String[] args) throws java.lang.Exception {
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    while (size > 0) {
        System.out.println(Main.ZeroCount(reader.nextInt()));
        size--;
    }
}

I did it with 1) long vs int; 2) i*=5 vs while loop with Math.pow(a,b) function; 3) Math.floor(c/d) vs simple c/d (because in Java integer dividing works as floor function) and some other simple checks what can go wrong.

Any ideas? Thanks!


Solution

  • Its a really small mistake.

    In function ZeroCount, replace i < num by i <= num

    public static int ZeroCount (int num)
    {
        int zeros = 0;
        for (int i =5; i <= num; i*=5)
            zeros = zeros + (int)Math.floor(num/i);
        return zeros;
    }