アットウィキロゴ

ouchi > Practice > Study04-04

  1. import java.util.Scanner;
  2.  
  3. /** 素数であるか否かの判定を行います **/
  4. public class PrimeNumber {
  5. public static void main(String[] args) {
  6. int input;
  7. Scanner scan = new Scanner(System.in);
  8. System.out.print("正の整数を入力: ");
  9. input = scan.nextInt();
  10.  
  11. boolean result = true;
  12. if (input < 2) {
  13. result = false;
  14. } else if (input == 2) {
  15. result = true;
  16. } else if (input % 2 == 0) {
  17. result = false;
  18. } else {
  19. for (int i = 3; i < input; i += 2) {
  20. if (input % i == 0) {
  21. result = false;
  22. break;
  23. }
  24. }
  25. }
  26.  
  27. if (result) {
  28. System.out.println(input + "は素数です.");
  29. } else {
  30. System.out.println(input + "は素数ではありません.");
  31. }
  32.  
  33. }
  34. }
  35.  
最終更新:2013年05月15日 18:12