Java:由于超时,对N系列求和失败 [英] Java : Summing the N series fails due to timeout

查看:65
本文介绍了Java:由于超时,对N系列求和失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在hackerrank网站上,有一个名为在数学下总结N系列"部分的任务.这是相同的 https://www.hackerrank.com/的链接挑战/求和n系列/问题

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

推荐答案

最后解决了.看看.

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

这篇关于Java:由于超时,对N系列求和失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆