Home > Enterprise >  Printing prime factors of numbers in C
Printing prime factors of numbers in C

Time:05-10

The code fits the first number and prints it constantly. how can i fix this?

int count = 0;
for (int i = 0; i <= 20; i  ) {
    for (count = 2; i > 1; count  ) {
        while (i % count == 0) {
            printf("%d ", count);
            i = i / count;
        }
    }
}

CodePudding user response:

The values in each iteration are as follows.

  1. count = 0; i = 0; Doesn't enter the second for.
  2. count = 0; i = 1; Doesn't enter the second for.
  3. count = 0; i = 2; Enters the second for. count = 2;
  4. 2 % 2 == 0 - Enters the while.
  5. i = 2 / 2; 1 % 2 == 1; Doesn't enter the while.
  6. Back to the second for - count = 3;, i = 1; Doesn't enter the second for.
  7. Back to the first for - i < 20;, so i = 2.
  8. count = 2; i = 2; and we are back to step 4, with an infinite loop.

This might be what you are looking for -

int j, count = 0;
for (int i = 20; i > 0; i--)
{
    printf("\n%d: ", i);
    for(count = 2, j = i; j > 1; count  )
    {  
        while(j % count == 0)
        {
            printf("%d ", count);
            j = j / count;
        }  
    } 
}

CodePudding user response:

Define a function that checks whether a given number n is prime:

bool is_prime(int n)
{
    if (n < 2) return false;
    for (int i = 2; i <= n/i;   i) // Doing i*i<=n may overflow
        if (n % i == 0) return false;
    return true;
}

And then call it like:

for (int i = 0; i <= 20; i  )
    if(is_prime(i))
        printf("%d\n", i);

Or more directly (i.e. without a function):

int main(void)
{
    int mark;
    for (int n = 2; n <= 20; n  ) {
        mark = 1;
        
        for (int i = 2; i*i <= n;   i)
            if (n % i == 0) mark = 0;
        
        if (mark) printf("%d\n", n);
    }
}
  •  Tags:  
  • c
  • Related