Java program to print the first n prime numbers

package com.physicsinfo;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int flag=0, limit, count=0;
        System.out.print("Enter how many prime numbers do you want to have printed: ");
        Scanner sc = new Scanner(System.in);
        limit = sc.nextInt();
        System.out.println("Here are your first "+ limit + " prime numbers:");

        for(int n=2;n<10000;n++){ // 0 and 1 are not prime numbers.
            if(count==limit){break;}
            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) { //prime numbers aren't divisible by any other number apart from 1 and the number itself
                    flag = 1;}
            }
        if (flag==0){
            System.out.print(n +" ");
            count++;
            if (count%10==0){
                System.out.println(" ");
            }
        }
        else {flag=0;}
        }
        }
    }

Leave a Comment

Your email address will not be published.