Write a program to find the divisors of a positive Integer

By | September 29, 2021 Problem Statement

We need to write a program, that accepts a positive integer value from the user and print all the possible divisors of that number (excluding the number itself).

For example

Input: 100
Output : 1 2 4 5 10 25 50

Algorithm

The problem statement is quite straightforward and beginner-level. To solve this problem all we need is a loop and a conditional if statement.

As the problem statement state that all we need to do is find all the divisors except for the number itself. So we need a loop from range 1 to half of the number entered by the user. Because a number’s all possible divisors can be the number itself and less than half of it.

C program to find the divisors of a Positive Integer

#include <stdio.h>

int main()
{
int num, i;
//input the number
printf("Enter a positive integer value: ");
scanf("%d",&num);

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

return 0;
}

Output

Enter a positive integer value: 100
1 2 4 5 10 20 25 50

C++ program to find the divisors of a Positive Integer

#include<iostream>

using namespace std;
int main()
{
int num;

//input the positive integer
cout<<"Enter a Positive Integer Number: "; cin>>num;

for(int i=1; i<=num/2; i++)
{
if(num%i==0)
{
cout<<i<<" ";
}
}
return 0;
}

Output:

Enter a Positive Integer Number: 100
1 2 4 5 10 20 25 50

Python:

# input number
num = int(input("Enter a Positive Integer Number: "))

for i in range(1, (num//2)+1):
if num%i==0:
print(i, end =" ")

Output:

Enter a Positive Integer Number: 100
1 2 4 5 10 20 25 50

Wrapping Up!

Now let’s wrap up this programming tutorial on “Write a program to find the divisors of a positive integer”. To find all the divisors of a number n we just need to calculate all smaller numbers that can divide the number n completely. If we look closely all the divisor of a number lies between 1 to half of the number itself, which save the time and we just need to create a loop that would iterate n/2 time. 