Java : 由于超时,对 N 系列求和失败

Java : Summing the N series fails due to timeout

在 hackerrank 网站上有一个任务叫做求和数学部分下的 N 系列。这是 link 相同的 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();
    }
}