All factors (divisors) of a number – CSKC
Sign In

Search

Code Learning #CPP#1584    siteicon   siteicon  

All factors (divisors) of a number

Printing all factors or divisors of an integer number.

Learning Objectives

  • Concept of factor or a divisor.
  • Concept of mod operator usage for checking a factor.
  • Concept of making a program efficient by using a loop that runs till half only if some constraints are known.

Program Approach

  • Begin dividing the given number from 1 and go till up to half of the number..
  • A number that can fully divide the given number in the numerator, leaving a remainder 0 is a divisor or factor.
  • Last factor is the number itself, so it can be printed outside the loop.

Source Code

TC++ #1584

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

for(int i=1;i<=n/2;i++)
This loop runs till half of the number as largest but one divisor is the never more than half of the number.
if(n%i==0) cout<<i<<” “;
A factor or divisor is essentially the one which leaves a remainder of 0 when the number is divided with it. ” ” space after printing i has been given to allow showing a space between all numbers output.
cout<<n<<endl;
Since the largest factor or divisor is number itself, we just print the largest number outside the loop.

Notes

  • Going till mid way is because the constraint of last but one divisor is pre known to us. we can also write this loop alternatively till the loop reaches the number and not print the last number ourside the loop as follows.for(int i=1;i<=n;i++) if(n%i==0) cout<<i<<” “;


Suggested Filename(s): factors.cpp, divisors.cpp



Share

Created: 2-Dec-2017 21:36 | Updated: 15-Sep-2018 13:51|