简体   繁体   English

[Java] [Spoj挑战]超过了时限-如何使其更快?

[英][Java][Spoj challenges] Time Limit Exceeds - How to make it faster?

My problem is that my code works perfectly when executed on an IDE But it exceeds the the time limit on Spoj. 我的问题是,我的代码在IDE上执行时可以正常工作,但是超过了Spoj的时间限制。 I am not getting any hint on how to make it more efficient. 我没有任何关于如何提高效率的暗示。 Spoj challenge Spoj挑战

Here is my code : 这是我的代码:

import java.util.Scanner;

public class Factorial {

    public static int getDecomposition(int a) {
        int count = 0;
        int result = a;
        while (result % 5 == 0) {
            result /= 5;
            count++;
        }
        return count;
    }

    public static void main(String[] args) throws Exception {

        Scanner scan = new Scanner(System.in);
        int testCases = scan.nextInt();
        int sum[] = new int[testCases];
        int nums[] = new int[testCases];
        for (int i = 0; i < testCases; i++) {
            nums[i] = scan.nextInt();
        }
        for (int i = 0; i < testCases; i++) {
            for (int j = 5; j <= nums[i]; j = j + 5) {
                sum[i] += getDecomposition(j);
            }
            System.out.println(sum[i]);
        }
    }
}

I'm thinking: Take 60 as an example (this is one of the example inputs in the linked challenges ). 我在想:以60为例(这是链接挑战中的示例输入之一)。 You are correct in the assumption in your code that for each number from 1 to 60 you only need to consider how many times it's divisible by 5, since there will always be enough numbers divisible by 2 that you will have this many zeroes. 您在代码中的假设中是正确的,对于从1到60的每个数字,您只需要考虑将其除以5的次数,因为总会有足够的被2除的数字,所以您会有这么多的零。 So how many of the numbers from 1 through 60 are divisible once by 5? 那么从1到60的数字中有多少可以被5整除? Answer: 60 / 5 = 12. Out of those 12, how many are divisible by 5 once more? 答案:60/5 =12。在这12个中,有多少个又可以除以5? 12 / 5 = 2 (ignore any remainder). 12/5 = 2(忽略任何余数)。 Add the 12 and the 2 (= 14) to record that until now we know that the factorial of 60 is divisible by 5 14 times. 加上12和2(= 14)以记录到现在为止,我们知道60的阶乘可被5 14整除。 And out of those 2, how many are divisible a third time? 在这2个中,有多少个是第三次可整除的? 2 / 5 = 0. Once we've reached 0, we're done. 2/5 =0。一旦我们达到0,就完成了。 The answer was 14 (this agrees with the answer in the example in the link). 答案是14(这与链接示例中的答案一致)。

So make an algorithm out of this way of finding the answer. 因此,通过这种寻找答案的方式来制定算法。 I think it will be somewhat faster than the program you have posted. 我认为它会比您发布的程序快一些。

It may also be that you can find a not too complicated formula for the sum I am calculating so you can avoid looping altogether. 对于我正在计算的总和,您可能还会发现一个不太复杂的公式,因此可以避免完全循环。 And maybe you can find some inspiration here: Geometric progression . 也许您可以在这里找到一些启发:几何级数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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