Need help making prime numbers row in {c}
Go to solution
Solved by Nineshadow,
You could use the sieve or Eratosthenes to generate primes efficiently. That sounds like what you are trying to do , I think.
The sieve of Eratosthenes works this way :
Given a number , p , it's obvious that any multiple of p won't be prime. So, if we were to mark off the multiples of all numbers smaller than our limit, we would be left only with prime numbers.
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
- Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
- Initially, let p equal 2, the smallest prime number.
- Starting from 2p, enumerate the multiples of p by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
- Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
Anyway, a really easy function to get the n-th prime would be :
int nthPrime(int n) { int x, count; for(x = 2, count = 0; count < n; ++x) { if (isPrime(x)) { ++count; } } return x-1;}
Not too efficient though.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now