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)
...



  1. public class C1
  2. {
  3. public static void main(String[] args)
  4. {
  5. int count = 1;
  6. int[] prime = new int[2];
  7. for(int i = 1 ;i <= 1000 ; i++ )//設定範圍從1-1000
  8. {
  9. boolean a = isPrimeNumber(i);//呼叫 isPrimeNumber 判斷是否為質數
  10. if(a == true && count == 1 )
  11. {
  12. prime[0] = i ;
  13. count = count + 1;
  14. }
  15. else if(a == true && count == 2 )
  16. {
  17. prime[1] = i ;
  18. count = count + 1;
  19. }
  20. else if(a == true && count > 2)
  21. {
  22. System.out.println("(" + prime[0] + "," + prime[1] + ")" );//印出答案
  23. prime[0] = prime[1];//印完後往前挪一個
  24. prime[1] = i;//新找到的數字寫近來
  25. }
  26. }
  27. }
  28. public static boolean isPrimeNumber(int number)
  29. {
  30. boolean bool = false ;
  31. int remainder = 0;
  32. int factor = 0 ;
  33. for(int i = 1 ; i <= number ; i++)//計算此數的因數個數
  34. {
  35. remainder = number % i;
  36. if(remainder == 0)
  37. {
  38. factor = factor + 1;
  39. }
  40. }
  41. if(factor == 2)
  42. {
  43. bool = true ;
  44. remainder = 0;
  45. factor = 0 ;
  46. }
  47. else if(factor != 2)
  48. {
  49. bool = false ;
  50. remainder = 0;
  51. factor = 0 ;
  52. }
  53. return bool ;
  54. }
  55. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

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