Java 求整数的素数因子 公开课练习{ 公共静态void main(字符串[]args){ 整数; int num=2;//要测试素数的数字 int count=0;//计算素数的个数 扫描仪键盘=新扫描仪(System.in); System.out.println(“请输入一个数字”); 整数=键盘.nextInt(); 而(count

Java 求整数的素数因子 公开课练习{ 公共静态void main(字符串[]args){ 整数; int num=2;//要测试素数的数字 int count=0;//计算素数的个数 扫描仪键盘=新扫描仪(System.in); System.out.println(“请输入一个数字”); 整数=键盘.nextInt(); 而(count,java,Java,循环条件意味着打印第一个“x”素数,因此如果输入60,它将打印前60个素数。即2,3,5,7,11 请像这样修改代码以获得所需的输出(只需替换整个循环) while(num请格式化代码并添加更好的描述以获得帮助。当你说最小因子时,你希望它有多小?有多少?…60还有多少其他素因子?为什么不使用像Fermat这样的基本因子分解方法?我还没有学过Fermat方法。我需要使用我所学的!@madhawapriyashantha这与OP quest相同ion用这个替换循环。谢谢你的回答。我只是想知道它怎么知

循环条件意味着打印第一个“x”素数,因此如果输入60,它将打印前60个素数。即2,3,5,7,11

请像这样修改代码以获得所需的输出(只需替换整个循环)


while(num请格式化代码并添加更好的描述以获得帮助。当你说最小因子时,你希望它有多小?有多少?…60还有多少其他素因子?为什么不使用像Fermat这样的基本因子分解方法?我还没有学过Fermat方法。我需要使用我所学的!@madhawapriyashantha这与OP quest相同ion用这个替换循环。谢谢你的回答。我只是想知道它怎么知道什么时候在5停止,而不继续其他素数因子,例如6,10,15等?6,10,15不是素数。首先6,10,15不是素数…其次它不在5停止,它完成整个循环直到60,如示例中所示,但它不打印这些e number,因为我们有isPrime&&integer%num==0,以确保打印的num必须是素数,并且必须将整数除以0的余数。否则它将不会被打印。”for(int i=2;i
public class Exercise {

    public static void main(String[] args) {

        int integer;
        int num = 2;//a number to be tested for primeness
        int count = 0;//count the number of prime numbers

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a number");
        integer = keyboard.nextInt();

        while (count <= integer) {
            boolean isPrime = true;//is current number prime
            //test wether number is prime

            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {//if true number is not prime
                    isPrime = false;//set is prime to false
                    break;//exit the loop
                }
            }

            if (isPrime) {
                count++;
                System.out.print(num);
            }

            num++;
        }
    }
}
while (num <= integer) { //Changed the condition here to 
        //stop when the number reached integer and not count 
        boolean isPrime = true;//is current number prime
        //test wether number is prime

        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {//if true number is not prime
                isPrime = false;//set is prime to false
                break;//exit the loop
            }
        }
        if (isPrime && integer % num == 0) {// added an additional check that
        // print the number only if it is prime and 
        // it is divides the integer with an remainder of 0
            System.out.println(num);
        }
        num++;
}