C program to find all prime factors of any number

Write a C program to enter any number and find all Prime factors of the number. C program to list all prime factors.
Example: Prime factors of 10 are 2 and 5.

Required knowledge:

Basic C programming, If else, For loop

Prime factors:

Factors of any number that are prime numbers are called as Prime factors of that number.
Example: 2 and 5 are the prime factors of 10.

Before finding all Prime factors you must know how to find factors of a number in C and how to check whether a number is Prime number or not in C.

Program:

/**
 * C program to find all prime factors of any number
 */

#include <stdio.h>

int main()
{
    int i, j, num, isPrime;

    /*
     * Reads a number from user
     */
    printf("Enter any number to print Prime factors: ");
    scanf("%d", &num);

    printf("\nAll Prime Factors of %d are: \n", num);

    /*
     * Finds all Prime factors
     */
    for(i=2; i<=num; i++)
    {
        /*
         * Checks if i is a factors of num
         */
        if(num%i==0)
        {
            /*
             * If i is a factor then check whether it is Prime or not
             */
            isPrime = 1;
            for(j=2; j<=i/2; j++)
            {
                if(i%j==0)
                {
                    isPrime = 0;
                    break;
                }
            }

            /*
             * If i is Prime then print i
             */
            if(isPrime==1)
            {
                printf("%d\n", i);
            }
        }
    }

    return 0;
} 

Note: For checking whether a number is Prime or not we just need to check that the number should not be divisible by any number between 2 to n-1. Apart from that you can also check between 2 to n/2. Since any number more than (n/2)+1 cannot be exactly divided by n except self n.

Output
X
_
Enter any number to print Prime factors: 15

All Prime Factors of 15 are:
3
5

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment