Search code examples
crecursionwhile-loopfactorsprime-factoring

why it's showig wrong output for prime factors?


I made this program to find prime factors of a number, but when i am running this code it's giving the wrong output. I have debugged this code and also the logic is correct. what i found is that, when "x == 1" the the program misbehaves. I am not able to find the answer.

#include<stdio.h>
void prime(int );
main()
{
    int num;

    printf("Enter a number to find its prime factors: ");
    scanf("%d", &num);

    printf("\nPrime factors of %d are: \n", num);

    prime(num);
}

void prime(int x)
{
    int i = 2;

    while(x != 1)
    {
        if(x % i == 0)
        {
            printf("%d, ", i);

            x = x / i;
            prime(x);
        }

        else
        {
            i++;
        }

    }
}

Solution

  • You should break from your loop once you find the first divisor. Otherwise, your outer method call will continue searching for divisors of your x even though it's no longer needed:

    void prime(int x) {
        if (x == 0) {
            printf("All prime numbers are prime factors of 0");
            return;
        }
    
        if (x == INT_MIN) {
            printf("Please provide a number larger than %i", INT_MIN);
            return;
        }
    
        x = abs(x);
        int i = 2;
        while(x != 1) {
            if(x % i == 0) {
                printf("%d, ", i);
    
                x = x / i;
                prime(x);
                break; // break here
            }
            i++;
        }
    }
    

    UPDATE

    However, recursion is not actually needed here - instead you could use a simple iterative algorithm as below:

    void prime(int x) {
        if (x == 0) {
            printf("All prime numbers are prime factors of 0");
            return;
        }
    
        if (x == INT_MIN) {
            printf("Please provide a number larger than %i", INT_MIN);
            return;
        }
    
        x = abs(x);
        int i = 2;
        while (x != 1) {
            if (x % i == 0) {
                printf("%d, ", i);
                x = x / i;
            }
            i++;
        }
    }