0

我只需要将因子输出为素数。

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a number:");
    int theNum = keyboard.nextInt();

    int i;

    System.out.println("\nThe prime factors of " + theNum + " are:");
    for(i=1; i <= theNum/2; i++)

        if(theNum % i == 0)
    {

    System.out.print(i + " ");

    }
    }
}
4

1 回答 1

0

You basically just need to check for prime numbers

Some prime-number check function I copied from here:

boolean isPrime(int n) {
    //check if n is a multiple of 2
    if (n%2==0) return false;
    //if not, then just check the odds
    for(int i=3;i*i<=n;i+=2) {
        if(n%i==0)
            return false;
    }
    return true;
}

Then just add the isPrime(i) check:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a number:");
    int theNum = keyboard.nextInt();

    System.out.println("\nThe prime factors of " + theNum + " are:");

    for(int i = 1; i <= theNum / 2; i++)
      if (theNum % i == 0 && isPrime(i))
        System.out.print(i + " ");
}

Test.

于 2013-03-31T21:54:17.413 回答