New to programing and to this forum. Hoping to get some feedback on my code. I want to find all prime numbers below 25. The code I have compiled currently lists the prime numbers it found repeatedly. Can't understand why...would really appreciate some guidance.
Because you're having a number output every time it proves that it isn't evenly divisible by the divisor, not just when it is prime you are also incorrectly testing for primeality. For example, '9' isn't prime but your program will output it when you test '9' against '2', '4', '5','6','7' and '8'. You should run through all of the divisors before you output the number.
Thanks, I changed it a bit to better test for prime numbers using sqrt(i). New code below...however still don't understand how to stop it from adding the same number to the list.
Try using a vector and every time you get a new prime number, add it to the vector. Then whenever you output a number, check that the number isn't already in the vector before you output it, if it is, don't output it.
I would prefer std::vector instead if at all possible:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
std::vector<int> primes;
for (int i = 2; i <= 25; ++i)
{
for (int divisor = 2; divisor <= i; ++divisor)
{
if (i % divisor == 0)
break;
elseif (divisor + 1 > sqrt(i))
{
primes.push_back(i);
std::cout << i << '\n';
break;
}
}
}
But if you must use an array, you'll have to keep track of the last index yourself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int primes[50]; // Plenty of space, just in case :)
int numPrimes = 0;
for (int i = 2; i <= 25; ++i)
{
for (int divisor = 2; divisor <= i; ++divisor)
{
if (i % divisor == 0)
break;
elseif (divisor + 1 > sqrt(i))
{
primes[numPrimes] = i;
++numPrimes; // Or you could just say 'primes[numPrimes++] = i;'
std::cout << i << '\n';
break;
}
}
}