Find Divisors of a Number in Java

This illustrates finding divisors of a number (int) in Java using simple and dead easy logic. Here is the code.








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

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

    // Create Scanner object for taking input
    Scanner s=new Scanner(System.in);

    // Read an int
    int n=s.nextInt();
   
        // Loop from 1 to 'n'
        for(int i=1;i<=n;i++)
        {
   
            // If remainder is 0 when 'n' is divided by 'i',
            if(n%i==0)
            {
            System.out.print(i+", ");
            }
        }
   
    // Print [not necessary]   
    System.out.print("are divisors of "+n);
   
    }
}

Sample Output


Enter the number
98
1, 2, 7, 14, 49, 98, are divisors of 98

The % symbol is used to find the remainder, the condition here is checked whether the remainder is 0. If the condition is satisfied i.e. if the remainder is 0, then the number is divisible by n. As this is a logic it can be applied not only in Java but other programming languages too for finding the divisors of a given number.

No comments: