【问题标题】:Need to output all prime numbers [duplicate]需要输出所有素数[重复]
【发布时间】:2013-03-31 21:57:56
【问题描述】:

对于示例 60,答案应该是 2 2 3 5,但它只会出现 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 + " ");
        }
    }
}

【问题讨论】:

  • 完全不同的代码
  • 我只是快速使用了他的代码,他显示了 2 以 2**2 的方式使用了两次的事实,但我希望它出现 2(这里有一个空格)2
  • 有什么办法可以让它显示数字的所有素数,在 60 的情况下是 2 2 3 5
  • @user2230190 所以,既然你知道count 的值是你想要打印2 的次数,你怎么能利用它呢? for 循环可能吗?
  • 你能把它写成代码吗?我是新手,还不完全了解所有类型的代码

标签: java


【解决方案1】:

问题在于,一旦发现 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 + " ");
            }
        }
    }

【讨论】:

  • Héctor van den Boorn 你就是男人
【解决方案2】:

如果你想用不同的方式来做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 2022-01-01
    • 2012-11-08
    • 2013-04-10
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多