Java : Summing the N series fails due to timeout

喜欢而已 提交于 2019-12-13 23:23:18

问题


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


来源:https://stackoverflow.com/questions/53959621/java-summing-the-n-series-fails-due-to-timeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!