Write a JAVA program to find the divisors of a given number.
- Divisor is a number that divides another number without a reminder or a number that divides an integer evenly.
Ex: 10/2= 5 (Here 2 is divisor.)
- Positive Divisor of a number N will be greater than or equal to 1 and less than or equal to number N.
- For Ex: Say Number is 4. Divisor of 4 will be 1,2 and 4.
- To get the divisor of a number N, we should divide N by all numbers in between 1 and N including 1 and N.
- We will use modulus operator which gives reminder. If reminder is zero, we can say given number is divisible by another number.
- For ex: 10%2= 0 (10 is divisible by 2 without a reminder)
- 11%2=1 (11 is divisible by 2 with a reminder as 1)
- A given number N can be divisible by another number Y without any reminder if Y is greater than or equal to 1 and less than or equal to N/2.
- In first logic, our loop will continue till counter equals to number which will make logic time consuming.
- We can reduce the loop iteration by half just by putting logic 2.
- For every divisor Y of
N, there is also a corresponding divisor
N/Y. Thus to find all pairs of divisors, you need only to loop from 1 to the square root N.
- This will be more optimal solution and interviewer will expect to write this logic.
If you have any other logic of solving above problem, please comment. It is always better to know more logic.
If you like my posts, please like, comment, share and subscribe.