C Program to Find the Factors of a Number

Factors of a Number in C

 

Here, in this page we will discuss the program to find factors of a number in C programming language. We will discuss different methods to find the factors of the given number.

Example :

  • Input : 10
  • Output : 1, 2, 5, 10
Factors of a number in C

Method 1 :

  • Run a loop from i=1 to i=n.
  • For, every i-th number check,
  • If (num%i==0) then, print that number.

Time and Space Complexity :

  • Time Complexity : O(n)
  • Space Complexity : O(1)
Factors of num

Code to Find Factors of a Number in C

#include<>stdio.h

int main(){

  int num = 10;
  for(int i=1; i<=num; i++){
     if(num%i==0)
     printf("%d ", i); 
   }
}
Output :

1  2 5 10

Method 2 :

  • Run a loop from i=1 to i=sqrt(n).
  • For, every i-th number check,
  • If (num%i==0) then, check if(num/i != i) then print i, otherwise print i and n/i

Time and Space Complexity :

  • Time Complexity : O(sqrt(n))
  • Space Complexity : O(1)
Factors of a number

Code in C

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

int main(){

  int num = 10;

  for(int i=1; i<=sqrt(num); i++){
     if(num%i==0){
      if(num/i ==i )
        printf("%d ", i);

     else printf("%d %d ", i, num/i);
  }
}
}
Output :

1  10 2 5 

Method 3 :

  • Run a loop from i=1 to i=sqrt(n).
  • For, every i-th number check,
  • If (num%i==0) then,  print i
  • Now, handle condition if(i-(num/i)==1) then decrement i.
  • Now, run a loop that will terminate when i < 1,
  • Check if (num%i==0) then print(num/i).

Time and Space Complexity :

  • Time Complexity : O(sqrt(n))
  • Space Complexity : O(1)

Code to Find Factors of a Number in C

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

int main(){

 int num = 10;

 int i;
 for(i = 1; i <= sqrt(num); i++)
 {
 if (num % i == 0)
 printf("%d ", i); 
 }

 if(i - (num/i) == 1) 
 i--;

 for( ; i>=1; i--)
 {
 if (num % i == 0)
 printf("%d ", num/i);
 }
}
Output :

1 2 5 10