Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java แสดงตัวประกอบของเลข (Factors of a Number)


ในบทความนี้ เราจะทำความเข้าใจวิธี แสดงตัวประกอบ (Factors) ของเลขที่กำหนด

นิยาม: ตัวประกอบ (Factors) คือจำนวนที่หารเลขนั้นลงตัว (ไม่เหลือเศษ)

ตัวอย่าง: ตัวประกอบของ 12 คือ 1, 2, 3, 4, 6, 12

ตัวประกอบน้อยที่สุดคือ 1, ตัวประกอบมากที่สุดคือตัวเลขเอง

ตัวอย่าง Input และ Output

Input:

Input : 45

Output:

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

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร my_input, i
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - วนลูป for i = 1 ถึง my_input ถ้า my_input % i == 0 แสดงว่า i เป็นตัวประกอบ
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - หยุด

ตัวอย่างที่ 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 + " ");
            }
        }
    }
}

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

ตัวอย่างที่ 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 + " ");
            }
        }
    }
}

Output

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