-2

for the example 60 the answer should be 2 2 3 5 but it only comes up with 2 3 5.

import java.util.Scanner;

public class PrimeFactor {

    public static void main(String[] args) {

        System.out.print("Enter a positive number: ");

        Scanner scanner = new Scanner (System.in);

        int number = scanner.nextInt();

        int count;

        for (int i = 2; i<=(number); i++) {
            count = 0;

            while (number % i == 0) {
                number /= i;
                count++;
                    }

            if (count == 0) {
                    continue;
            }
            System.out.print(i + " ");
        }
    }
}
4

2 回答 2

0

如果您想以不同的方式进行操作:

import java.util.*;
import java.lang.*;

class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
            System.out.print("Enter a positive number: ");
            Scanner scanner = new Scanner (System.in);

            int number = scanner.nextInt();

            int divisor = 2;
            while(number != 1) {
            if(number % divisor == 0) {
                System.out.println(divisor + " ");
                number /= divisor;
            }
            else {
                divisor++;
            }
        }
    }
}
于 2013-03-31T22:20:49.037 回答
0

问题是一旦它发现 60 可以被 2 整除,它就会继续将其除以 2(在这种情况下是两次)。

将 while 语句的最后一个括号放在 System.out.print 之后,它可以工作:

public static void main(String[] args) {

        System.out.print("Enter a positive number: ");

        Scanner scanner = new Scanner (System.in);

        int number = scanner.nextInt();

        int count;

        for (int i = 2; i<=(number); i++) {
            count = 0;

            while (number % i == 0) {
                number /= i;
                count++;


            if (count == 0) {
                    continue;
            }
            System.out.print(i + " ");
            }
        }
    }
于 2013-03-31T22:13:48.310 回答