2013-03-31 95 views
-2

爲例如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 + " "); 
     } 
    } 
} 
+0

完全不同代碼 – user2230190

+0

我剛剛使用他的代碼,他顯示的事實是,2以2 ** 2的方式使用兩次,但我希望它來了2(在這裏有一個空間)2 – user2230190

+0

有沒有什麼辦法可以讓我它顯示在60的情況下所有數字的素數2 2 3 5 – user2230190

回答

0

出現的問題是,一旦它發現60整除2,它一直分爲2(在這種情況下是兩次)。

的地方是System.out.print AFTER while語句的最終支架和它的工作原理:

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

Héctorvan den Boorn你是男人 – user2230190

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