简体   繁体   中英

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

This code computes the largest prime factor of a number. This gives an error 5/6 times from an Online Judge. I can't figure out the exception or error. Please help...

You should reset temp to 0 for each case. Example input:

2 7 4

Expected output:

7
2

Actual output

7
7

Hope it helps.

Such errors are easier to make when you declare your variables earlier than you need them. Instead of

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

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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