Problem:

**Write a JAVA program to find the divisors of a given number.**

Solution:

- 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.)

**Logic 1:**

- 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)

Java Code:

Output:

Logic 2:

- 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.

Java Code:

Output:

Logic 3:

- 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.

Java code:

Output:

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.

#HappyCoding

#### Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning