Prime Number Generator Logic

后端 未结 15 2230
旧时难觅i
旧时难觅i 2021-01-07 04:10

I am supposed to make a class PrimeNumberGenerator which has a method nextPrime that will print out all prime numbers up to a number the user input

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 04:48

    package test;
    
    import java.util.Scanner;
    
    public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner reader = new Scanner(System.in);  // Reading from System.in
            System.out.println("Please Enter number you wanted prime number to be generated");
            int n = reader.nextInt();
            reader.close();
    
            Prime t1 = new Prime();
            for (int i = 2; i <= n; i++) {
                t1.x(i);
            }
        }
    
        public void x(int n) {
            // TODO Auto-generated method stub
            // TODO Auto-generated constructor stub
            int k = n - 1;
            int f = 0;
            if (n == 2) {
                f = 1;
            }
            for (int i = 2; i <= k; i++) {
                if (n % i == 0)
                    break;
                else if (k == i) {
                    f = 1;
                }
            }
            if (f == 1) {
                System.out.println("is prime" + n);
            }
    
        }
    }
    

提交回复
热议问题