C Programming: Find all prime factors of a given integer

C Programming Mathematics: Exercise-35 with Solution

Write a C program that accepts an integer and find all prime factors of the integer.

Prime factors of a number are those factors that are prime numbers. 2 and 4 are factors of 4, where 2 is considered the prime factor.

Test Data:
(77) -> 7, 11
(12) -> 2, 2, 3
(45) -> 3, 3, 5

Sample Solution:

C Code:

#include <stdio.h>
#include <math.h>

int main(void) {
  int n;
  printf("Input an integer: ");
  scanf("%d", &n);
	  if (n>0)
       while (n%2==0) 
          printf("2 "); 
            n /= 2; 
        for (int i = 3; i <= sqrt(n); i+= 2) 
            while (n%i == 0) 
               printf("%d ",i);
                n /= i; 
        if (n > 2) 

Sample Output:

Input an integer: 78
2 3 13


Flowchart: Find all prime factors of a given integer

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Kth smallest number in a multiplication table.
Next: Count common factors of two integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
    ptr = 0;// oops, I meant *ptr = 0

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q