# Finding Prime Numbers

March 10. 2020 0 Comments

- Posted in:
- C#

So - I got it into my head to create a function that would find prime numbers. There was no real reason to do so - it was just one of those coding ear worms that bug you until you actually do something about it.

After staring at a blank IDE for a while, I decided what I

I decided that the best way to go for this project would be to determine the next prime number from a given integer. That way, I could generate lists and other such nonsense. I settled on the following sequence:

The premise of the function is that we want to find the next prime number, not whether the input number itself is prime.

After staring at a blank IDE for a while, I decided what I

*really*wanted to do was create an app that would give me*n*number of prime numbers in a list.**Rules for optimization:**

- Don't optimize.
- Optimize later.

I decided that the best way to go for this project would be to determine the next prime number from a given integer. That way, I could generate lists and other such nonsense. I settled on the following sequence:

public int nextPrime(int lastNo)

{

int currentNo = lastNo;

bool isNotPrime = true;

while (isNotPrime)

{

isNotPrime = false;

currentNo++;

for (int i = 2; i < currentNo; i++)

{

if (currentNo % i == 0)

{

isNotPrime = true;

break;

}

}

return currentNo;

}

}

The premise of the function is that we want to find the next prime number, not whether the input number itself is prime.

- We create a copy of the input number (
*currentNo*). - We create a conditional check (is the number not prime?) and set to true. This is so we can pass into the first conditional.
- While the conditional is true (the number is not prime)
- Set the conditional to false. We are setting the assumption that the number is indeed a prime.
- increment the
*currentNo*value by 1. - Create a
**for-loop**to go through all of the numbers between 2 and the*currentNo*minus 1. - If the modulus of
*currentNo*divided by the increment value (i) equals 0, then the number cannot be prime, so we set the test flag as true and break from the loop. Otherwise, we continue iterating through the set range of numbers until we exhaust it, or we manage to change the flag. - If the test flag is true, re-run the sequence until it is not.
- Return the first value that results in the
**for-loop**not changing the test flag to true.

So - fairly elegant, but far from optimized. For single checks, this function preforms very fast. But what if we want to find the next 100, 1000, 10000, or 1 million prime numbers in a sequence?

(To be continued . . .)