Print all divisors of a number in python

This is a Python Program to generate all the divisors of an integer.

Problem Description

The program takes a number and generates all the divisors of the number.

Problem Solution

1. Take the value of the integer and store it in a variable.
2. Use a for loop and if statement to generate the divisors of the integer.
3. Print the divisors of the number.
4. Exit.

Program/Source Code

Here is source code of the Python Program to generate all the divisors of an integer. The program output is also shown below.

 
n=int[input["Enter an integer:"]]
print["The divisors of the number are:"]
for i in range[1,n+1]:
    if[n%i==0]:
        print[i]

Program Explanation

1. User must first enter the value and store it in a variable.
2. Use a for loop to generate numbers from 1 to n.
3. Using an if statement check if the number divided by i gives the remainder as 0 which is basically the divisor of the integer.
4. Print the divisors of the number.

Runtime Test Cases

 
Case 1:
Enter an integer:25
The divisors of the number are:
1
5
25
 
Case 2:
Enter an integer:20
The divisors of the number are:
1
2
4
5
10
20

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Next Steps:

  • Get Free Certificate of Merit in Python Programming
  • Participate in Python Programming Certification Contest
  • Become a Top Ranker in Python Programming
  • Take Python Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.

Given a natural number n, print all distinct divisors of it.

Examples:

 Input : n = 10       
 Output: 1 2 5 10

 Input:  n = 100
 Output: 1 2 4 5 10 20 25 50 100

 Input:  n = 125
 Output: 1 5 25 125

Note that this problem is different from finding all prime factors.

A Naive Solution would be to iterate all the numbers from 1 to n, checking if that number divides n and printing it. Below is a program for the same:

C++

#include

using namespace std;

void printDivisors[int n]

{

    for [int i = 1; i

Javascript

function printDivisors[n]

{

    for [i=1;i

Javascript

function printDivisors[n]

{

    for[let i = 1; i

Chủ Đề