Home »
Java Programs »
Java Basic Programs
Java program to count factors of a given number
Here, we are implementing a java program that will read an integer number and count its all factors. If a number is divisible by 4 different numbers than factors of that number will be 4.
Submitted by IncludeHelp, on December 10, 2017
Problem statement
Given an integer number and we have to count its all factors using java program.
Example
Input:
Enter the number : 45
Output:
Number of factors of is : 6
Explanation:
45 is divisible by: 1, 3, 5, 9, 15, 45
Thus, factors will be 6
Program to count all factors of a number in java
import java.util.Scanner;
public class CountFactors
{
public static void main(String[] args)
{
// create object
Scanner in = new Scanner(System.in);
// enter integer number here.
System.out.print("Enter the number : ");
int x = in.nextInt();
System.out.println("Number of factors of is : " +result(x));
}
// create function to find the factors of given number.
public static int result(int num)
{
int ctr = 0;
for(int i=1; i<=(int)Math.sqrt(num); i++)
{
if(num%i==0 && i*i!=num)
{
ctr+=2;
}
else if (i*i==num)
{
ctr++;
}
}
return ctr;
}
}
Output
First run:
Enter the number : 45
Number of factors of is : 6
Second run:
Enter the number : 158
Number of factors of is : 4
Java Basic Programs »