galacticfan galacticfan - 3 months ago 19
C Question

Printing Out Prime Numbers in C

I'm attempting to print out the prime numbers up to a certain value that is obtained from the user. I imagine there is something wrong with my for loop if I only ever receive an answer of 1?

#include <stdio.h>
#include <cs50.h>

int main (void)
{
printf("Length: ");
int length = GetInt();

bool notPrime = false;

for (int i = 1; i < length; i++)
{
for (int k = 1; k <= i/2; k++)
{
if (i % k == 0)
{
notPrime = true;
break;
}
else
{
notPrime = false;
}
}
if (notPrime == false)
{
printf("%d ", i);
}
}
printf("\n");
}

Answer

In the internal loop:

for (int k = 1; k <= i/2; k++) 

You are starting with k = 1 and testing if k divides i. 1 divides any integer, so the answer will always be "non prime", which is not the case (remember the definition of prime number). Start from 2:

for (int k = 2; k <= i/2; k++) 
Comments