2014年12月27日 星期六

java程式設計題目---公式計算【梅森質數(使用method)】

A prime number is called a Mersenne prime(梅森質數) if it can be written in the form 2^p-1 for some positive integer p.
Write a program that finds all Mersenne prime with p<=31 and displays the output as follows:
p     2^p-1
2         3
3         7
5         31
...


public class C1 
{
 public static void main(String[] args) 
 {  
  int number = 2;
  
  System.out.print("p     ");
  System.out.println("2^p-1");
  
  while(number <= 31)
  {
   int newnumber = (int)Math.pow(2, number) - 1;//計算2^p-1
     
      
   boolean a = isMersennePrimesNumber(newnumber);
   
   if(a == true)
   {
    System.out.print(number + "     ");
    System.out.println(newnumber); 
    
   }
   
   number ++ ;
  }
 }  
  public static boolean isMersennePrimesNumber(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-...