C Program to find prime factors of a number

How to write a C Program to Find Prime Factors of a Number using For Loop, While Loop, and Functions. In our previous article, we have already explained, How to write a program to Find Factors of a Number and Find Prime numbers.

C Program to Find Prime Factors of a Number Using While Loop

The below program allows the user to enter any integer value. Using this value, this program will find the Prime Factors of a number using While Loop.

#include <stdio.h>

int main()
{
    int Number, i = 1, j, Count;

    printf("Please Enter number to Find Factors  :  ");
    scanf("%d", &Number);

    while (i <= Number)
    {
        Count = 0;
        if(Number % i == 0)
        {
            j = 1;
            while(j <= i)
            {
                if(i % j == 0)
                {
                    Count++;
                }
                j++;
            }
            if(Count == 2)
            {
                printf("%d is a Prime Factor \n", i);
            }
        }
        i++;
    }

    return 0;
}

Output:

Please Enter number to Find Factors: 300
2 is a Prime Factor
3 is a Prime Factor
5 is a Prime Factor

 

C Program to find prime factors of a number using functions

 

#include <stdio.h>

void primeFactors(int Number)
{
    int i, Count = 0;

    for (i = 2; i <= Number/2; i++)
    {
        if(Number%i == 0)
        {
            Count++;
        }
    }
    if(Count == 0 && Number != 1 )
    {
        printf("\n%d is a Prime Number factor", Number);
    }
}


void findFactors(int Number)
{
    int i;

    for (i = 1; i <= Number; i++)
    {
        if(Number % i == 0)
        {
            primeFactors(i);
        }
    }
}


int main()
{
    int i, j, Number, count;

    printf("Enter number to Find it's Prime Factors :  ");
    scanf("%d", &Number);

    findFactors(Number);

    return 0;
}

 

Output:

Enter number to Find it’s Prime Factors: 315

3 is a Prime Number factor
5 is a Prime Number factor
7 is a Prime Number factor

Recommended Articles for you: