Find All the Factors of a Number using Java For and If loops
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 Facebook, Twitter, Tumblr.
Comments
Post a Comment