繁体   English   中英

我的最大质数程序中的错误是什么?

[英]What is the error in my Largest Prime Number program?

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 次。 我无法弄清楚异常或错误。 请帮忙...

对于每种情况,您都应该将 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM