Java : Summing the N series fails due to timeout

2019-09-22 12:21发布

问题:

In hackerrank website there is a task called Summing the N series Under Mathematics section. Here is link for the same https://www.hackerrank.com/challenges/summing-the-n-series/problem

I have tried many things. Finally came to point where some of my test cases are passing some are not due to timeout exception.

Here is the complete code. Please let me know what would be solution.

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();
    }
} 

回答1:

Finally it got solved. take a look.

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();
    }
}