Find divisors of a number java: In the previous article, we have seen Java Program to Check if All the Digits of a Number are in Decreasing Order
In this article we are going to count total numbers of divisors of a number in java.
Java Program to Count Total Number of Divisors of a Number
Approach:
- Ask the user to enter the number and store it
- Run a for loop from 1 to the entered number and count the numbers that leave a remainder of 0.
- Print the count/result.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Class to take input
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to check - ");
// Taking inout from user
int num = scan.nextInt();
int count=0;
// Loop to count the number of divisors
for(int i = 1; i<= num;i ++)
{
// Increments count if the number is divisible by i
if(num%i==0)
count++;
}
// Prints the result
System.out.print(num+" has "+count+" divisors.");
}
}
Output: Enter a number to check - 54 54 has 8 divisors.
Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.
Related Java Programs: