Java code for finding factors of a Number

Here we will see how to find factors of a number. JAVA code for finding possible factors of a number.

what are Factors ?

A factor can simply defined as a number which divides given number completely. Completely divisible in the sense remainder after division should be zero.

Example1:

number= 4

So for 4 we have following factors

4%1=0

4%2=0

4%4=0

Example2:

consider number=12

factors are

12%1=0 , 12%2=0, 12%4=0, 12%6=0, 12%12=0

so all the combinations mentioned above are factors of number 12.

Now from above examples it is clear that for any number there will be 2 fixed factors

1) 1

2) number itself

How to find factors ?

As we already understood what are factors, now how to find factors for number.

It’s very easy just start dividing the given number starting from 1 until number itself. For example if we wish to find factors for 10, we will start from 1 that is 10%1, 10%2, 10%3,10%4, 10%5, 10%6, 10%6, 10%7, 10%8, 10%9, 10%10.

so out of above combiations onw which gives ZERO as a remainder will be considered as factors of 10.

if we observe closely 10%1=0 , 10%2=0, 10%5=0, 10%10=0 are the 4 combinations which gives ZERO remainder, therefore 10 has got 4 factors and these are 1,2,5,10.

Example2: factors of 16

16%1=0, 16%2=0, 16%4=0, 16%8=0, 16%16=0

so 1, 2, 4, 8,16 are the factors of 16

Algorithm

  1. Read the number from keyboard
  2. Use a for loop starting from 1 running upto number itself
  3. if number / i gives ZERO as remainder, consider it as factor
  4. Print the factors accordingly

Also Read

Java Code for Fibanacci Series

Tech Mahindra off Campus Coding Question

Crack TCS Coding Round By solving These Questions

JAVA Code for Finding Factors

import java.util.*;
public class problem35 {
    public static void main(String[] args) {

        // code for finding factors of a NUMBER 

        System.out.println("Enter the number:");

        Scanner sc=new Scanner(System.in);

        int N=sc.nextInt();
        
        for (int i=1;i<=N;i++){

            if(N%i==0){
                System.out.println(i+" ");
            }
        }
    }
}

Want detailed explanation on above code, visit our channel for step by step explanation

1 thought on “Java code for finding factors of a Number”

  1. Pingback: Java code to find Factorial of Number - Is It Actually

Leave a Comment

Your email address will not be published. Required fields are marked *