2014年12月26日 星期五

java程式設計題目---數字處理【迴文質數判斷(使用method)】

A palindromic prime is a prime number and also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 100 palindromic prime numbers. Display 10 numbers line, separated by exactly one space, as follows:
2 3 5 7 11 101 131 151 181 191
313 353 373 383 727 757  787 797 919 929


public class C1 
{

 public static void main(String[] args) 
 {
  int countnumber = 0 ;
  int number = 2;
  
  while(countnumber < 100)
  {
   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)
   {
    boolean a = isPalindrom(number);//呼叫  isPalindrom 判斷此數是否為迴文數
    
    if(a == true)
    {
     countnumber++;//找到1個數所以要先加一
     
     //控制每行只印出10個數
     if(countnumber % 10 == 0)
     {
      System.out.println(number + " ");
      
      number++;
      
      //找到數字之後榆樹要記得將餘數和因數個數清0
      remainder = 0;
      factor = 0 ;      
     }
     else if(countnumber % 10 != 0)
     {
                        System.out.print(number + " ");
      
      number++;
      
      //找到數字之後榆樹要記得將餘數和因數個數清0
      remainder = 0;
      factor = 0 ;
     }         
    }    
   }   
  
   number++; //如股不是的話也要++才會換到下一個數   
  }
 
 }
 
 public static boolean isPalindrom(int number)
 {
  int inputnumber = number ;//要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!! 
  int[] array = new int[10];
  int i = 0;
  int z = number;  
  int count = 1;
  int t = 1;
  int result = 0;
  boolean bool = new Boolean(true) ;
  
  while(number > 0)
  {
   
   int a = number % 10;
   array[i] = a;
   z = number / 10 ;
   number = z;
   i++ ;
   count = count + 1; 
   
  }
  
  for(int a = count - 2 ; a >= 0 ; a--)
  {
   int c = array[a] * t ;
   result = result + c;
   t = t * 10;  
  }
  
  if( inputnumber == result )
  {
   bool = true ;
  }
  else if(inputnumber != result)
  {
   bool = false ;
  }  
        return bool; 
 }

}

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

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