简体   繁体   中英

java program to find prime factors of a number

public class PrimeFactor {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the number:");
    int num=input.nextInt();
    int factors;
    for(int i=1;i<num;i++)
    {
        factors=num%i;
        if(factors==0 && isPrime(factors))
        System.out.println(i+"");
    }
    input.close();
}
public static boolean isPrime(int n)
{
    boolean prime=true;
    for(int i=2;i<n;i++)
    {
        if(n%i==0)
        {
            prime=false;
            break;
        }

    }
    return prime;
}

}

I have written this code to find the prime factors of a number. The logic I have applied seems fine to me but the output is coming wrong.

for(int i=1;i<num;i++)
    {
        factors=num%i;
        if(factors==0 && isPrime(factors))
        System.out.println(i+"");
    }
    input.close();

factors is the remainder of num / i . So if factors returns 0 , then you are passing 0 to your method isPrime() , which makes no sense. I think you might want to be passing i to isPrime , not factors .

So your loop should be the same thing, but with a different parameter passed to the isPrime() function.

for(int i=1;i<num;i++)
    {
        factors=num%i;
        if(factors==0 && isPrime(i))
        System.out.println(i+"");
    }
    input.close();

DanGordon is correct in saying you should pass i instead of factors to isPrime() . That prevents composite numbers from being outputted, but that still doesn't fix the issue that the inputted number won't be displayed even if it is prime. The problem there lies with your for loop. i<num tells the program to iterate through the for loop only as long as i is less than the number entered, so, once i is equal to the num , it breaks out of the loop. If you change i<num to i<=num , it will ensure the loop runs when i is equal to the entered number as well, and therefore it should display the number entered if that number is prime.

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