我的Largest Prime Number计划中的错误是什么?

时间:2016-10-01 13:29:49

标签: java primes

public class LargestPrimeFactor {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int cases = scan.nextInt();
    int num = 0, temp = 0;
        while(cases!=0) {
        num = scan.nextInt();
        for(int i=2; i<=num; i++)
            if(num%i==0) {
                if(isPrime(i)) {
                    if(temp<i)
                        temp = i; //to always have the largest factor
                }
                num/=i; // to reduce the iterations for a large number.
            }
        System.out.println(temp);
        cases--;
    }
}

public static boolean isPrime(int num) {
    if ( num > 2 && num%2 == 0 )
        return false;
    int top = (int)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2)
        if(num % i == 0)
            return false;
    return true; 
}
}

此代码计算数字的最大素数因子。 这给出了在线评判的5/6次错误。我无法弄清楚异常或错误。 请帮忙......

1 个答案:

答案 0 :(得分:1)

对于每种情况,您应该将temp重置为0。 示例输入:

2 7 4

预期产出:

7
2

实际输出

7
7

希望它有所帮助。

当您在变量之前声明变量时,这些错误更容易实现。而不是

int num = 0, temp = 0;
    while(cases!=0) {
    num = scan.nextInt();

while (cases != 0) {
    int num = scan.nextInt();
    int temp = 0;