Prime factors of a number

Program to display prime factors

C program to display prime factors of a number

Factors of a number that are prime numbers are called Prime factors of that number. For example: 2 and 5 are the prime factors of 10.

Logic to check prime factors of a number
Step by step descriptive logic to find prime factors.

  1. Input a number from the user. Store it in some variable say num.
  2. Run a loop from 2 to num/2, increment 1 in each iteration. The loop structure should look like for(i=2; i<=num/2; i++).

You may think why loop from 2 to num/2? Because the prime number starts from 2 and any factor of a number n is always less than n/2.

  1. Inside the loop, first check if iis a factor of num or not. If it is a factor then check it is prime or not.

Print the value of i if it is prime and a factor of num.

/**
 * C program to find all prime factors of a given number
 */
#include <stdio.h>
#include<conio.h>
Void main()
{
    int i, j, num, isPrime;
    /* Input a number from user */
printf("\n\t\t\t...Welcome To EduNews.Tech... ");

    printf("Enter any number to print Prime factors: ");
    scanf("%d", &num);
    printf("All Prime Factors of %d are: \n", num);
    /* Find all Prime factors */
    for(i=2; i<=num; i++)
    {
        /* Check 'i' for factor of num */
        if(num%i==0)
        {
            /* Check 'i' for Prime */
            isPrime = 1;
            for(j=2; j<=i/2; j++)
            {
                if(i%j==0)
                {
                    isPrime = 0;
                    break;
                }
            }
            /* If 'i' is Prime number and factor of num */
            if(isPrime==1)
            {
                printf("%d, ", i);
            }
        }
    }
    printf("\n\n\n\t\t\tThankyou for Joining Us !");
    printf("\n\t\t\t!Regards EduNews !");
getch();
}

Program Output:

prime factors

I hope this post helps you to understand the “Prime factors of a number” and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *