2014年12月27日 星期六

java程式設計題目---數字處理【雙生質數(使用method)】

Twin primes(雙生質數) are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are twin primes. Write a program to find all twin primes less than 1,000. Display the output as follows:
(3,5)
(5,7)
...



public class C1 
{
 public static void main(String[] args) 
 {
  int count = 1;
  int[] prime = new int[2]; 
  
  for(int i = 1 ;i <= 1000 ;  i++ )//設定範圍從1-1000
  {
   boolean a = isPrimeNumber(i);//呼叫  isPrimeNumber 判斷是否為質數  
   
   if(a == true && count == 1 )
   {
    prime[0] = i ;
    count = count + 1;     
   }
   else if(a == true && count == 2 )
   {
    prime[1] = i ;
    count = count + 1;
   }
   else if(a == true && count > 2)
   {
    
    System.out.println("(" + prime[0] + "," + prime[1] + ")" );//印出答案
    prime[0] = prime[1];//印完後往前挪一個
    prime[1] = i;//新找到的數字寫近來
   }   
  }  
 } 
 
 public static boolean isPrimeNumber(int number)
  {
   boolean bool = false ;
   int remainder = 0;
   int factor = 0 ;
   
   for(int i = 1 ; i <= number ; i++)//計算此數的因數個數
   {
    remainder = number % i;
    if(remainder == 0)
    {
     factor = factor + 1;
    }
    
   }
   if(factor == 2)
   {
       bool = true ; 
       
       remainder = 0;
    factor = 0 ;
   }
   else if(factor != 2)
   {
    bool = false ;
    
    remainder = 0;
    factor = 0 ;
   }
  
   return bool ;
  }
}

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...