Detailed Print – CSKC
Sign In

Search

siteicon
Solved Problem#CPP#2016 Back

Problem Statement - Print all divisors and count of divisors

Write a c++ program to ask an integer number from the user and then print all its divisors in one line, followed by the count of divisors. The output should be as per example given below.

Enter an integer :45
The divisors of 45 are –
1 3 5 9 15 45
The count of divisors = 6

Solution

		 

Click to open popup

Run Output

Enter an integer :45
The divisors of 45 are -
1 3 5 9 15 45
The count of divisors = 6

Solved Problem Understanding

cout<<“The divisors of “<<n<<” are -“<<endl;
This line is before the for loop as it has to printed before the list of divisors.

for(int i=1;i<=n;i++)
{
  if(n%i==0)
  {
  cout<<i<<” “;
  cnt++;
  }
}
This loop begins with 1 as first divisor of a number is 1. Then it checks by dividing the number with every successive number after 1 using the condition (n%i==0) for every number. When condition matches then the given denominator must be divisor, so i is printed. Also the variable count is increment so that it can later be printed outside the loop.

cout<<endl<<“The count of divisors = “<<cnt<<endl;
The count is printed after the divisors are printed. That is why this is done outside the loop.

 

Notes

  • Some books/web documents do not count the number itself as the divisor. As per exact definition it must also be counted as the divisor.
  • This program can also give you prime number check. If the divisor count for a number is 2 (1 and the number itself) then the number is considered as prime number. With this logic 1 is not considered as a prime number, which is the current definition.

Common Errors

  • Placement of related cout before the loop, inside the loop and outside the loop is important. Students generally do mistakes on this account.
  • Placement of braces inside the if condition are also important as both divisor output and count increment are done when the divisibility condition is true.