Java Program to Display Factors of a Number - The Coding Shala

Home >> Java Programs >> Display Factors of a Number

 Hey there, welcome back to another post. In this post, we are going to learn how to find all the factors of a given natural number in Java.

Java Program to Display Factors of a Number

First, let's understand what are the factors or divisors. If a number1 divides the number2 completely without any reminders, then number1 is a factor of number2. For example:

The factor of 10 is 1, 2, 5, 10 because all these numbers divide 10 without any reminders.

Java Program to Print Factors of a Number using for Loop

Using the for loop from 1 to the number itself, we can print all the factors.

Java Program: 

import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void printFactors(int num) {
        System.out.println("Factors of " + num + " are: ");

        for (int i = 1; i <= num; i++) {
            if (num % i == 0) {
                System.out.print(i + " ");
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int num = sc.nextInt();
        printFactors(num);
    }
}

Output: 

Enter a number
15
Factors of 15 are: 
1 3 5 15 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala