Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package ktltbai9;
- import java.util.Scanner;
- /**
- *
- * @author Admin
- */
- public class bai9 {
- public static void main(String[] args) {
- int m = 0;
- while (true) {
- System.out.println("Nhập số: ");
- int n = nhapso();
- switch (n) {
- case 1:
- m = nhapso();
- break;
- case 2:
- sntVongLap(m);
- break;
- case 3:
- sntDeQuy(m);
- break;
- case 4:
- System.exit(0);
- default:
- continue;
- }
- }
- }
- public static int nhapso() {
- int n;
- try {
- n = Integer.parseInt(new Scanner(System.in).nextLine());
- } catch (NumberFormatException e) {
- System.out.println("Nhập lại đúng định dạng");
- return nhapso();
- }
- return n;
- }
- private static void sntDeQuy(int n) {
- if (n < 2) {
- return;
- }
- if (ktraSNT(n)) {
- System.out.println(n);
- sntDeQuy(n - 1);
- } else {
- sntDeQuy(n - 1);
- }
- }
- private static boolean ktraSNT(int n) {
- if (n < 2) {
- return false;
- } else if (n == 2 || n == 3) {
- return true;
- }
- for (int i = 2; i <= Math.sqrt((double) n); i++) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
- private static void sntVongLap(int n) {
- while (true) {
- if (n < 2) {
- return;
- }
- if (ktraSNT(n)) {
- System.out.println(n);
- n--;
- } else {
- n--;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment