In this article, we will understand how to display factors of a number. Factor are number that divides another number or expression evenly.
Factors are the numbers we multiply to get another number. For example, if we multiply 3 and 5, we get 15. We say, 3 and 5 are factors of 15. Alternatively, factors of a number are those numbers which divide that number without leaving any remainder. For example, 1, 2, 3, 4, 6, and 12 are factors of 12 as all of them divide it evenly.
The largest and smallest factors of a number. The largest factor of any number is the number itself and the smallest factor is 1.
- 1 is the factor of every number.
- So, for example, the largest and smallest factors of 12 are 12 and 1.
Below is a demonstration of the same −
Input
Suppose our input is −
Input : 45
Output
The factors of 45 are: 1 3 5 9 15 45
Algorithm
Step 1 - START Step 2 - Declare two integer values namely my_input and i Step 3 - Read the required values from the user/ define the values Step 4 - Using a for loop, iterate from 1 to my_input and check if modulus my_input value and ‘i’ value leaves a reminder. If no reminder is shown, then it’s a factor. Store the value. Step 5 - Display the result Step 6 - Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .
import java.util.Scanner; public class Factors { public static void main(String[] args) { int my_input, i; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the number : "); my_input = my_scanner.nextInt(); System.out.print("The factors of " + my_input + " are: "); for (i = 1; i <= my_input; ++i) { if (my_input % i == 0) { System.out.print(i + " "); } } } }
Output
Required packages have been imported A reader object has been defined Enter the number : 45 The factors of 45 are: 1 3 5 9 15 45
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
import java.util.Scanner; public class Factors { public static void main(String[] args) { int my_input, i; my_input = 45; System.out.println("The number is defined as " +my_input); System.out.print("The factors of " + my_input + " are: "); for (i = 1; i <= my_input; ++i) { if (my_input % i == 0) { System.out.print(i + " "); } } } }
Output
The number is defined as 45 The factors of 45 are: 1 3 5 9 15 45