输出大于某个正整数n的最小质数(1除外

输出大于某个正整数n的最小质数(1除外

V1.0

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int m = s.nextInt();
        while (true) {
            m++;
            boolean flag = judge(m);
            if (flag) {
                System.out.println(m);
                break;
            }
        }
    }

        public static boolean judge ( int n){
            for (int k = 2; k < n; k++) {
                if (n % k == 0)
                    return false;
            }
            return true;
        }

    }

V2.0:进一步简化主方法代码

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Print();
    }

    public static void Print(){
        Scanner s = new Scanner(System.in);
        int m = s.nextInt();
        while (true) {
            m++;
            boolean flag = judge(m);
            if (flag) {
                System.out.println(m);
                break;
            }
        }
    }
    public static boolean judge ( int n){
        for (int k = 2; k < n; k++) {
            if (n % k == 0)
                return false;
        }
        return true;
    }

}

V3.0:优化Print方法代码

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Print();
    }

    public static void Print(){
        Scanner s = new Scanner(System.in);
        int m = s.nextInt();
        while (!judge(++m)){
            
        }
        System.out.println(m);
    }
    public static boolean judge ( int n){
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

}

你可能感兴趣的:(学习题目)