SPOJ的主要生成器在Idone.com上运行正常时会发出运行时错误

时间:2016-05-19 08:39:35

标签: java

我在提交此代码时遇到运行时错误,而在idone.com和我的本地计算机上运行正常。我想我在某处省略了边界条件,但无法找到位置。

这是我的代码。

package com.prime.src;

import java.util.Scanner;

class PrimeSieve {

static boolean[] isPrime = new boolean[100000];

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    for (int j = 2; j < isPrime.length; j++) {
        isPrime[j] = true;
    }


    if(scanner.hasNextInt()){
        int N = Integer.parseInt(scanner.nextLine());

        int lowerBound = 0;
        int upperBound = 0;
        for (int i = 0; i < N; i++) {
            lowerBound = scanner.nextInt();
            upperBound = scanner.nextInt();
            printPrime(lowerBound, upperBound);
        }
    }
    else{
        System.out.println();
    }

}

public static void printPrime(long lowerBound, long upperBound){

    for (int i = 2; i * i <= upperBound; i++) {

        if (isPrime[i]) {
            for (int j = i; i * j <= upperBound; j++) {
                isPrime[i * j] = false;
            }
        }
    }

    boolean[] range = new boolean[(int) (upperBound + 1)];

    for (int i = (int) upperBound; i >= lowerBound; i--) {
        range[i] = true;
    }

    for (int j = 2; j * j < upperBound; j++) {
        if (isPrime[j]) {
            long num1 = lowerBound / j;
            long num2 = num1 * j;
            long limit = num2;
            for (long i = lowerBound; limit <= upperBound; i++) {
                if (limit != j) {
                    range[(int) limit] = false;
                }
                limit = limit + j;
            }
        }

    }

    for (long i = lowerBound; i <= upperBound; i++) {
        if (i == 1)
            continue;
        if (range[(int) i]) {
            System.out.println(i);
        }
    }


}

} 

1 个答案:

答案 0 :(得分:0)

AS SPOJ在异常处理方面并不是很冗长,您可以将代码包装在主方法中,以获取更多信息:

public static void main(String[] args) throws IOException
    {
        try {
            //the original code in your main-Method goes here
        } catch(Exception e){
            e.printStackTrace();
            return;
        }
    }

我怀疑它是一个包装超时,因为Scanner不是很快。