Q:

Java program to count factors of a given number

belongs to collection: Java Basic Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Program to verify answers of answer sheets of N st... >>
<< Java program to print \'W\' pattern usin...