How to Display Factors of a Number in C++

In this tutorial, we will be learning about how to display the factors of a number in C++.

Displaying factors of a number in C++

Before moving into displaying factors of a number, if you are a beginner, please go through the basics.

for loop in C++

Description

Factors are the numbers that are multiplied to get a number.

example: 1, 15 are the factors of 15 which implies 1*15=15.

Header Files

we only require the standard header file over here..

<iostream>(Standard input output stream)

Time Complexity

0(n)

Here, for every value of i we are checking whether that is a factor or not.

Code

The sample code is as follows…

#include <iostream>
using namespace std;

int main()
{
    int n;
    //taking an integer from a user 
    cout<<"Enter a number\n";
    cin>>n;
    cout<<"The factors of a given number are\n";
    for(int i=1;i<=n;i++)
    {
        //if n is divided by i and which gives remainder as 0.then, we print i.
        if(n%i==0)
        cout<<i<<" ";
    }

    return 0;
}

Output:

Enter a number
15
The factors of a given number are
1 3 5 15

Explanation:

Here, Firstly a Positive integer is Entered by a user (i.e..n)

Then

for(int i=1;i<=n;i++)
    {
        //if n is divided by i and which gives remainder as 0.then, we print i.
        if(n%i==0)
        cout<<i<<" ";
    }

Here, the above for loop is executed by initializing i=1 and checking n(the number) is divided by i and which gives the remainder as 0. and if both the conditions are proper, then i will be the factor of n.then, we just print the value of i.

In every iteration the value of i is being incremented(incremented by 1).

And then, this process is executed until i <=n.

Leave a Reply

Your email address will not be published.