Ok, so I know lots of people have posted about how to find prime numbers up to a certain number, and I can do that, however If I wanted to output a certain number of prime numbers so that the user inputs say 6, it would out put 2, 3, 5, 7, 11, 13.. not just 2, 3, 5 (up to that number). Any ideas? please help!

Dani AI

Generated

Many replies here already point in the right direction; this short note ties them together and gives a simple, correct approach.

There are two different problems: "primes up to N" (test every number 2..N) and "first N primes" (produce N primes, stopping when the count reaches N). and are correct that you should count outputs and stop when the counter reaches the requested number. A very common bug — seen in 's get_prime() logic that reports the 25th prime as 95 — is modifying the candidate inside the inner divisor loop without resetting the divisor. That lets the new candidate escape the remaining small-divisor checks and be accepted as prime. Fix: when a divisor is found, advance to the next candidate and restart divisor testing from the first divisor (or from the smallest prime), do not increment both candidate and divisor together.

For practice: use one of two reliable strategies.

  • Simple and robust: trial division by previously found primes, testing divisors only up to sqrt(candidate). Works fast for moderate N and is easy to implement.
  • Fast for large N: use a sieve (Eratosthenes or segmented sieve). Use the prime-number-theorem as a guide to choose a sieve limit and add a safety margin.

Example (compact C++):

#include <iostream>
#include <vector>
#include <cmath>

std::vector<int> first_n_primes(int n){
  std::vector<int> primes;
  if (n<=0) return primes;
  primes.reserve(n);
  int cand = 2;
  while ((int)primes.size() < n){
    bool is_prime = true;
    int r = (int)std::sqrt(cand);
    for (int p : primes){
      if (p > r) break;
      if (cand % p == 0){ is_prime = false; break; }
    }
    if (is_prime) primes.push_back(cand);
    cand += (cand==2) ? 1 : 2; // skip even numbers after 2
  }
  return primes;
}

Debugging tips: test with known values (25th prime is 97), print candidate/divisor on failure, make sure counters are only incremented when a prime is confirmed (as pointed out), use int main() (see ), and prefer restarting the inner test when you change the candidate rather than continuing with stale divisor values.

Recommended Answers

All 17 Replies

Primes upto n

for ( i = 1 ; i < n ; i++ ) {
  if ( isPrime(i) )
}

Number of primes

i = 1
while ( x < n ) {
  if ( isPrime(i) ) x++
  i++
}

In other words, every time you output a value, add 1 to a counter. When it reaches you 'magic number' exit the loop.

I have this so far....It doesnt seem to like me, can anyone help?

//Nth Prime Number Search


//This is a program which will display the Nth prime number to the user
#include <iostream>
using namespace std;

void primeTest(int);

int main()
{
  system("clear");
  cout << "Please give me the _th number that you would like " << endl << "(eg. 5 for the 5th Prime number) or hit -1 to exit" << endl;
  int n;
  cin >> n;
  
  if(n<=0)
    {return 1;}
  else
    primeTest(n);
  return 0;
}
 
void primeTest(int n)
{
  int temp = 2;

  for (int counter=1; counter<=n; counter++)
    {
      cout << "Prime number " << counter << " is " << temp << endl;
      counter ++;

      for (int divisor=2; divisor <= temp; divisor++)
    {
      if (divisor % temp ==0)
        {
          break;
        }
    }
      temp++;
    }
}

you are adding counter twice in your loop, need to remove one.

void primeTest(int n)
{
  int temp = 2;

  for (int counter=1; counter<=n; counter++)
    {
      cout << "Prime number " << counter << " is " << temp << endl;
    //  counter ++; need to be comented out or removed.

      for (int divisor=2; divisor <= temp; divisor++)
    {
      if (divisor % temp ==0)
        {
          break;
        }
    }
      temp++;
    }
}

ok so i got the counter part fixed, now the prime numbers wont count tho...

Instead of this

if(n<=0)
    {return 1;}
  else
    primeTest(n);
  return 0;

do this:

if (n > 0)
{
    primeTest(n);
}
return 0;

It's simple and easy to read.

And:

for (int counter=1; counter<=n; counter++)

A for loop will not give you n primes, it will simply test the values 1 thru n for prime. Use a while loop instead.

well i thnk ths will solve ur prob...................

#include<stdio.h>
void prime_no(int n);
void main()
{
int n;
printf("ENTER THE NO. OF PRIME NOS. U WANNA SEE");
scanf("%d",&n);
prime_no(n);
return;
}
void prime_no(n)
{
int i,j,count;
for(i=2,count=1;count<=n;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
break;
}
if(j==i)
{printf("%d\n",i);
count++;
}
}
}

well i thnk ths will solve ur prob...................

If you are going to do people's homework for them, at least give them good code in a well formatted style.

Better yet, let them write the code and you suggest options so they can learn to do it themselves...

You could create a lazy list datatype that only produces values when you request them -- and whose values it produces are the natural numbers. Then run the sieve of Eratosthenes on it. Then peel off the first 6 elements of the list.

Or you could use a vector that you grow whenever you need more elements and use the sieve of eratosthenes on that, or some modification thereof.

An alternative is to exploit the prime number theorem. Out of x numbers, the proportion of primes is ~(x/log(x)), so allocate a vector with max(C,ceil(1.15 * n*(1+log n))) elements if you want n primes, for some constant C that's large enough, and then use the sieve of Eratosthenes.

I guess this works better in a language that's lazy by default.

nPrimes n = take n (nubBy (\x y -> y `mod` x == 0) [2..])

I keep getting stuck at number 25, where is says prime 25 is 95.....up until then it works great

//Prime numbers
//March 26th 2007
//CPSC121-03

//This is a program which will display the Nth prime number to the user
#include <iostream>
using namespace std;

int get_prime(int);

int main()
{
  system("clear");
  int n;
  do 
    {
      cout << "Please give me the _th number that you would like " << endl << 
              "(eg. 5 for the 5th Prime number) or hit -1 to exit" << endl;
      cin >> n;
      system("clear");
      
      if (n == 1)
    cout << "Prime number 1 is 2" << endl;
      else if(n<1)
    return 1;
      else if (n>1)
    {
      get_prime(n);
      cout << "Prime number " << n << " is " << get_prime(n) << endl;
    }
    } 
  while (n>0);
  return 0;
}

int get_prime(int n)
{
  int prime = 1; 
  for (int counter=2; counter<=(n); counter++)
    {
      prime += 2;
      int divisor=2;
      while(divisor < prime)
         {
      if ((prime % divisor != 0))
        divisor +=1;
      else
        {
          prime += 2;
          divisor +=2;
        }
         }     
    }
  return (prime);
}
while (n>0);

What the.... :?:
Wouldn't a simple getchar() suffice?

What the.... :?:
Wouldn't a simple getchar() suffice?

hell, before i had a for statement only with breaks, but my teacher didnt like it........dont worry bout the int main...im pretty sure it works right

hell, before i had a for statement only with breaks, but my teacher didnt like it........dont worry bout the int main...im pretty sure it works right

Being "pretty sure" and actually working right may be 2 different things. Remove that while , it's a very bad practice, and add getchar() instead.

And I think your problem is in this section:

else
    {
        prime += 2;
        divisor +=2;
    }

Look carefully at what happens after this code is executed. Run through your code on paper to see what happens.

what does getchar() mean?

If you are going to do people's homework for them, at least give them good code in a well formatted style.

Better yet, let them write the code and you suggest options so they can learn to do it themselves...

ok sir!!!!!!!!!!!!!!
i will remember tht..........
thnk u.........

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.