Find All the Factors of a Number using Java For and If loops



What are the factors of a Number? A factor is a Number that does not leave a remainder when it divides the number. 

So Factors of 4 can be 1, 2, 4. Easy right?
What about 20? 1,2,4,5,10,20.

Now, What about factors of 859? That's difficult right? You might have to do a lot of calculations to find that one. 

That's why its an easy but popular Interview Question. We are going to write some simple Java code today to find out all the factors of a number. 

It's really easy if you grasped the basic concept correctly. 

The Factor of a Number, is a Number which does not leave a remainder.

Which Operator can help us to find the Remainder? Simple its the % operator.

(Number % factor) will give us a Remainder. 

So, the heart of our code is going to be:

//if remainder is 0, means the number is a factor
if(num%i==0)

We will be checking the Remainder for all Numbers starting from 1 to the Number itself and store the factors (where Remainder is 0). 

ArrayList is a good Collection to store these factors. And then, we'll return the ArrayList for further processing.

Here is the code for your reference:

/**
 * Find all the factors of a Number
 * @author computengine.com
 * @param num
 * @return
 */
public static ArrayList<Integer> findFactors(int num){
	
	ArrayList<Integer> factors = new ArrayList<Integer>();
	
	//check the division of each number from 1 to the number itself
	for(int i=1;i<=num;i++) {
		//if remainder is 0, means the number is a factor
		if(num%i==0)
			factors.add(i);
	}
	
	return factors;
}

Now to run the code and check the output:

System.out.println("Factors of Number:"+findFactors(859).toString());

Here is the Output:

Factors of Number:[1, 859]

Another try, with a different number:

System.out.println("Factors of Number:"+findFactors(859).toString());

Factors of Number:[1, 2, 3, 4, 6, 7, 8, 12, 14, 16, 21, 24, 28, 42, 48, 56, 84, 112, 168, 336]

Super! We've successfully implemented the logic to find Factors of a Number.


Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblr.




Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

4 ways to add New Line Character to a String in Java