Home > Net >  I am trying to solve this question. But condition is dont touch listPrime function. Is it possible
I am trying to solve this question. But condition is dont touch listPrime function. Is it possible

Time:09-09

**Dont touch listPrime function just modify the main function.Also Must use listPrime to get return value ; Question from one of my senior classmate **

#include <iostream>
const int nmax = 100001;
bool isPrime[nmax];
int listPrime(int num){
 for(int i = 2; i<=num;i  ){
  isPrime[i] = true;
 }
 for(int i = 2; i<=num/2;i  ){
  if(isPrime[i]==true){
   for(int j =i*2;j<=num;j =i){
    isPrime[j] = false;
   }  
  } 
 }
 for(int i=2;i<=num;i  ){
  if(isPrime[i] == true){
   return i;
  }
 }
}

int main (){
 //Qn: Call the above function and get return all prime number lists from 1-100
 // but dont touch listPrime Function untill you think you can not do it
 return 0;
}

CodePudding user response:

You don't need to use the function's return value at all. I'm sure that final loop and return in the function is there to throw you off. It's completely pointless.

The function computes a prime sieve. If you just call it once, it'll generate the entire table for values up to whatever value you passed. So you may as well pass nmax to generate the entire table. Computing a sieve is very fast, especially for values as small as 100000.

Once the table is built, all you need to do is read the value at any valid index to know if that index is a prime number. It's unclear whether you want to show A) all primes up to 100; or B) the first 100 primes. I'll show both.

int main()
{
    listPrime(nmax);

    // Option A: Output primes up to 100
    for (int n = 0; n < 100; n  )
    {
        if (isPrime[n]) {
            std::cout << n << '\n';
        }
    }

    // Option B: Output first 100 primes
    for (int count = 0, n = 0; count < 100 && n < nmax; n  )
    {
        if (isPrime[n]) {
            count  ;
            std::cout << "Prime " << count << " is " << n << '\n';
        }
    }
}
  •  Tags:  
  • c
  • Related