简体   繁体   中英

I am not sure why I am getting a TLE for codechef

When I submit my solution to codechef, I keep getting a time limit error. I switched to buffered reader from scanner, but that did not fix it. I'm thinking it is in my algorithm, but I am not sure where, other than checking each 5 decrement could be unnecessary. Where is the issue I am having located so that I can figure out how to solve it?

Here is the link for reference: https://www.codechef.com/problems/FCTRL

Here is my code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class Factorial {
    public static void main(String[] args) throws IOException {
        BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

        //how many numbers follow
        int number = Integer.parseInt(keyboard.readLine());
        //stores zSum's to output later
        int[] answerArray = new int[number];

        for(int i = 0; i < number; i++) {
            //the number to compute factorial
            int n = Integer.parseInt(keyboard.readLine());

            // moves number to one ending in 5
            n -= n % 5;
            //stores number of zeros
            int zSum = 0;

            for (int j = n; j > 0; j -= 5) {

                //if a power of 5, add 1 to zSum
                for (int k = 5; k <= j; k *= 5) {
                    if (j % k == 0) {
                        zSum ++;
                    }
                }
            }
            answerArray[i] = zSum;
        }

        //println all values in array
        for (int i = 0; i < number; i++) {
            System.out.println(answerArray[i]);
        }
    }
}

Your complexity is to high,

for (int j = n; j > 0; j -= 5)

will do O(N) operations. Inner cycle will add log to complexity. You should write use some other approach. It can be done using O(log(N)) time for each testcase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM