Java程序显示数字的因子


在本文中,我们将了解如何显示数字的因子。因子是可以整除另一个数字或表达式的数字。

因子是我们相乘以得到另一个数字的数字。例如,如果我们将 3 和 5 相乘,我们得到 15。我们说,3 和 5 是 15 的因子。或者,一个数字的因子是可以整除该数字而没有余数的那些数字。例如,1、2、3、4、6 和 12 是 12 的因子,因为它们都能整除 12。

一个数字的最大和最小因子。任何数字的最大因子都是数字本身,最小因子是 1。

  • 1 是每个数字的因子。
  • 因此,例如,12 的最大和最小因子是 12 和 1。

以下是相同内容的演示 -

输入

假设我们的输入是 -

Input : 45

输出

The factors of 45 are: 1 3 5 9 15 45

算法

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

示例 1

在这里,输入是根据提示由用户输入的。您可以在我们的编码练习工具 运行按钮中实时尝试此示例。

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 + " "); } } } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

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

示例 2

在这里,整数已预先定义,其值在控制台中被访问和显示。

Open Compiler
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 + " "); } } } }

输出

The number is defined as 45
The factors of 45 are: 1 3 5 9 15 45

更新于:2022年2月22日

6000+ 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告