Question

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");
}
Was it helpful?

Solution

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++) 

OTHER TIPS

in the internal loop:

for(k=2; k<=sqrt(i); k++) 

will work.

You may have to check the special cases and you can start from 3. Also you can increment by 2 exluding the pair numbers:

for(int i = 1; i < length; i++){

    if(number < 2) prime = true; 
    if(number == 2) prime = false;
    if(number % 2 == 0) prime = false; 
    for (int k = 3; k <= i/2; k++){
        if(number % i == 0 ){ 
            prime = false;
            break;
        }
    }
    if (prime){
        printf("%d ", i);
    }
}

You should make the IF's out of the first bucle, and also you can change k <= i/2 -> sqrt(i)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top