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

輸出

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

在這裡,整數已預先定義,其值在控制檯中被訪問和顯示。

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+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.