简体   繁体   中英

Program to print first m prime numbers in the first n positive integers

Write a program to generate and print first m prime numbers in the first n positive integers.

Example: n=10,m=2 In a range of 1-10 natural numbers, I have to generate m=2(2 positive prime numbers) Input:10 2 Output:2 3

My Code: Note=Try to answer in java

import java.util.Scanner;
class Main5{
static Scanner sc=new Scanner(System.in);
 static boolean isPrime(int n){
     //since 0 and 1 is not prime return false.
     if(n==1||n==0) return false;

   //Run a loop from 2 to n-1
     
   for(int i=2; i<=n/2; i++){
       
       // if the number is divisible by i, then n is not a prime number.
       if(n%i==0)return false;
   }
   //otherwise, n is a prime number.
   return true; }

public static void main (String[] args)
   {
       int n=sc.nextInt();
       int m=sc.nextInt();
       //check for every number from 1 to N
       for(int i=1; i<=n; i++){
         if(i==m){
               break;
           }
           //check if current number is prime
           if(isPrime(i)) {
             System.out.print(i + " ");
           }
       }
   }
   }
  

Use another variable to hold the number of prime numbers you already found. Increments its value whenever you print a prime number. When the count variable primeFound==m break from the loop.
Also try to use the condition i*i<=n in the isPrime function as this reduces the runtime to O(√n) from O(n/2) . You can also use sieve of eratosthenes for the precomputation of the primes.
The code should be something like this:

import java.util.Scanner;
class Main5{
static Scanner sc=new Scanner(System.in);
 static boolean isPrime(int n){
     //since 0 and 1 is not prime return false.
     if(n<2) return false;

   //Run a loop from 2 to n-1
     
   for(int i=2; i*i<=n; i++){
       
       // if the number is divisible by i, then n is not a prime number.
       if(n%i==0)return false;
   }
   //otherwise, n is a prime number.
   return true; }

public static void main (String[] args)
   {
       int n=sc.nextInt();
       int m=sc.nextInt();
       int primeFound=0;
       //check for every number from 1 to N
       for(int i=1; i<=n; i++){
         if(primeFound==m){
               break;
           }
           //check if current number is prime
           if(isPrime(i)) {
             primeFound++;
             System.out.print(i + " ");
           }
       }
   }
   }

You could use that method but it will be slow for large numbers and you'll have to execute that code for every prime number query. If you have capacity and time, perhaps you could think about this technique instead: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM