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


  1. public class C1
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6. int countnumber = 0 ;
  7. int number = 2;
  8. while(countnumber < 100)
  9. {
  10. int remainder = 0;
  11. int factor = 0 ;
  12. for(int i = 1 ; i <= number ; i++)//計算此數的因數個數
  13. {
  14. remainder = number % i;
  15. if(remainder == 0)
  16. {
  17. factor = factor + 1;
  18. }
  19. }
  20. if(factor == 2)
  21. {
  22. boolean a = isPalindrom(number);//呼叫 isPalindrom 判斷此數是否為迴文數
  23. if(a == true)
  24. {
  25. countnumber++;//找到1個數所以要先加一
  26. //控制每行只印出10個數
  27. if(countnumber % 10 == 0)
  28. {
  29. System.out.println(number + " ");
  30. number++;
  31. //找到數字之後榆樹要記得將餘數和因數個數清0
  32. remainder = 0;
  33. factor = 0 ;
  34. }
  35. else if(countnumber % 10 != 0)
  36. {
  37. System.out.print(number + " ");
  38. number++;
  39. //找到數字之後榆樹要記得將餘數和因數個數清0
  40. remainder = 0;
  41. factor = 0 ;
  42. }
  43. }
  44. }
  45. number++; //如股不是的話也要++才會換到下一個數
  46. }
  47. }
  48. public static boolean isPalindrom(int number)
  49. {
  50. int inputnumber = number ;//要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!!
  51. int[] array = new int[10];
  52. int i = 0;
  53. int z = number;
  54. int count = 1;
  55. int t = 1;
  56. int result = 0;
  57. boolean bool = new Boolean(true) ;
  58. while(number > 0)
  59. {
  60. int a = number % 10;
  61. array[i] = a;
  62. z = number / 10 ;
  63. number = z;
  64. i++ ;
  65. count = count + 1;
  66. }
  67. for(int a = count - 2 ; a >= 0 ; a--)
  68. {
  69. int c = array[a] * t ;
  70. result = result + c;
  71. t = t * 10;
  72. }
  73. if( inputnumber == result )
  74. {
  75. bool = true ;
  76. }
  77. else if(inputnumber != result)
  78. {
  79. bool = false ;
  80. }
  81. return bool;
  82. }
  83.  
  84. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

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