【问题标题】:How do I make this output prime numbers as factors instead of all factors? [duplicate]如何将此输出素数作为因子而不是所有因子? [复制]
【发布时间】:2013-03-31 21:22:41
【问题描述】:

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

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 + " ");

    }
    }
}

【问题讨论】:

  • 永远不要使用.nextInt(),因为它很可能会在以后给您带来问题。始终使用.nextLine() 并将其解析为int
  • 我是编程新手,您可以将那行作为代码输入,以便我知道您的意思吗?
  • @syb0rg 您可能想要包含一个原因 - (类似的)...问题,例如如果您在同一个 Scanner 上使用 nextIntnextLinenextInt 不会' t 包括下一个行尾字符,因此您将在下一个 nextLine 调用中得到一个空行。
  • @Dukeling 我根本看不出使用nextInt() 的理由,而我可以使用nextLine 并从中解析我需要的所有信息。
  • @user2230190 String nextIntString = keyboard.nextLine();(获取单行数字)int nextInt = Integer.parseInt(nextIntString);(将字符串转换为整数)

标签: java


【解决方案1】:

你基本上只需要检查素数

我从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;
}

然后只需添加isPrime(i) 检查:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多