After staring at a blank IDE for a while, I decided what I reallywanted 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;
isNotPrime = false;
for (int i = 2; i < currentNo; i++)
if (currentNo % i == 0)
isNotPrime = true;
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 currentNovalue by 1.
- Create a for-loop to go through all of the numbers between 2 and the currentNominus 1.
- If the modulus of currentNodivided 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.