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

โปรแกรม Java ตรวจสอบเลขสมบูรณ์ (Perfect Number)


ในบทความนี้ เราจะเรียนรู้วิธีตรวจสอบว่าเลขใดเลขหนึ่งเป็น เลขสมบูรณ์ (Perfect Number) หรือไม่ เลขสมบูรณ์คือจำนวนเต็มบวกที่เท่ากับผลรวมของตัวประกอบ (factors) ของมัน ยกเว้นตัวมันเอง

ตัวอย่าง: 6 เป็นเลขสมบูรณ์ เพราะตัวประกอบคือ 1, 2, 3 และ 1+2+3 = 6

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

Input:

Enter the number : 496

Output:

The number 496 is a perfect number

อัลกอริธึม

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

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class PerfectNumber {
    public static void main(String args[]) {
        long my_input, my_sum;
        int i;
        my_sum = 0;
        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.nextLong();
        i = 1;
        while (i <= my_input / 2) {
            if (my_input % i == 0) {
                my_sum = my_sum + i;
            }
            i++;
        }
        if (my_sum == my_input)
            System.out.println("The number " + my_input + " is a perfect number");
        else
            System.out.println("The number " + my_input + " is not a perfect number");
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 496
The number 496 is a perfect number

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

import java.util.Scanner;
public class PerfectNumber {
    public static void main(String args[]) {
        long my_input, my_sum;
        int i;
        my_sum = 0;
        my_input = 496;
        System.out.println("The number is defined as " + my_input);
        i = 1;
        while (i <= my_input / 2) {
            if (my_input % i == 0) {
                my_sum = my_sum + i;
            }
            i++;
        }
        if (my_sum == my_input)
            System.out.println("The number " + my_input + " is a perfect number");
        else
            System.out.println("The number " + my_input + " is not a perfect number");
    }
}

Output

The number is defined as 496
The number 496 is a perfect number