簡體   English   中英

Java:由於超時,對 N 系列求和失敗

[英]Java : Summing the N series fails due to timeout

在hackerrank網站上有一個任務叫做Summing the N series Under Mathematics section。 這是相同的https://www.hackerrank.com/challenges/summing-the-n-series/problem 的鏈接

我嘗試了很多東西。 終於到了我的一些測試用例正在通過的地方,有些不是由於超時異常。

這是完整的代碼。 請讓我知道什么是解決方案。

public class Solution {

    static int mod = 1000000007;

    static int summingSeries(long t) { 
        long sum = 0;
        for (int i = 0; i < t; i++) {
            sum = ((t%mod)*(t%mod))%mod;
        }
        return (int)sum;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(scanner.nextLine().trim());

        for (int tItr = 0; tItr < t; tItr++) {
            long n = Long.parseLong(scanner.nextLine().trim());

            int result = summingSeries(n);

            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }

        bufferedWriter.close();
    }
} 

終於解決了。 看一看。

public class Solution {
    static int mod = 1000000007;
    static int summingSeries(long n) { 
        return (int)(((n % mod) * (n % mod)) % mod);
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(scanner.nextLine().trim());

        for (int tItr = 0; tItr < t; tItr++) {
            long n = Long.parseLong(scanner.nextLine().trim());

            int result = summingSeries(n);

            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }

        bufferedWriter.close();
    }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM