C Program to Find Prime Factors Of A Given Number

Prime factors of a number are those prime numbers which on multiplying together we get original number.

Prime factor examples:

Prime factors of 18 are = [2, 3, 3] so that 2 * 3 * 3 = 18 where 2 & 3 are prime numbers.

Prime factors of 4620 are: [2, 2, 3, 5, 7, 11]

This C program calculates list of all prime factors of a given number by user.

C Source Code: Prime Factors


#include<stdio.h>
/* FUNCTION PROTOTYPES */
void getPrimeFactors();
/* MAIN FUNCTION*/
int main()
{
 int number;
 printf("Enter number: ");
 scanf("%d", &number);
 /* FUNCTION CALL */
 getPrimeFactors(number);
 return 0;
}

/* FUNCTION DEFINITION */
void getPrimeFactors(int n)
{
    int i = 2, p[100], index=0;
    while(i*i <= n)
    {
        if(n%i==0)
        {
            p[index] = i;
            index++;
            n = n/i;
        }
        else
        {
            i = i+1;
        }
    }
    if(n>1)
    {
        p[index] = n;
    }
    /* Displaying results */
    printf("Prime factors are:\n");
    for(i=0;i<=index;i++)
    {
        printf("%d\t", p[i]);
    }
}

Output

Enter number: 12321
Prime factors are:
3       3       37      37