Wanderlust1998

Untitled

Apr 11th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package ktltbai9;
  7.  
  8. import java.util.Scanner;
  9.  
  10. /**
  11.  *
  12.  * @author Admin
  13.  */
  14. public class bai9 {
  15.  
  16.     public static void main(String[] args) {
  17.         int m = 0;
  18.         while (true) {
  19.             System.out.println("Nhập số: ");
  20.             int n = nhapso();
  21.             switch (n) {
  22.                 case 1:
  23.                     m = nhapso();
  24.                     break;
  25.                 case 2:
  26.                     sntVongLap(m);
  27.                     break;
  28.                 case 3:
  29.                     sntDeQuy(m);
  30.                     break;
  31.                 case 4:
  32.                     System.exit(0);
  33.                 default:
  34.                     continue;
  35.             }
  36.         }
  37.  
  38.     }
  39.  
  40.     public static int nhapso() {
  41.         int n;
  42.         try {
  43.             n = Integer.parseInt(new Scanner(System.in).nextLine());
  44.         } catch (NumberFormatException e) {
  45.             System.out.println("Nhập lại đúng định dạng");
  46.             return nhapso();
  47.         }
  48.         return n;
  49.     }
  50.  
  51.     private static void sntDeQuy(int n) {
  52.         if (n < 2) {
  53.             return;
  54.         }
  55.         if (ktraSNT(n)) {
  56.             System.out.println(n);
  57.             sntDeQuy(n - 1);
  58.         } else {
  59.             sntDeQuy(n - 1);
  60.         }
  61.     }
  62.  
  63.     private static boolean ktraSNT(int n) {
  64.         if (n < 2) {
  65.             return false;
  66.         } else if (n == 2 || n == 3) {
  67.             return true;
  68.         }
  69.  
  70.         for (int i = 2; i <= Math.sqrt((double) n); i++) {
  71.             if (n % i == 0) {
  72.                 return false;
  73.             }
  74.         }
  75.         return true;
  76.     }
  77.  
  78.     private static void sntVongLap(int n) {
  79.  
  80.         while (true) {
  81.             if (n < 2) {
  82.                 return;
  83.             }
  84.             if (ktraSNT(n)) {
  85.                 System.out.println(n);
  86.                 n--;
  87.             } else {
  88.                 n--;
  89.             }
  90.         }
  91.     }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment