ในบทความนี้ เราจะทำความเข้าใจวิธี แสดงเลขอาร์มสตรอง (Armstrong Numbers) ในช่วงที่กำหนด โดยใช้ฟังก์ชัน
นิยามซ้ำ: เลขอาร์มสตรอง 3 หลัก = ผลรวมของแต่ละหลักยกกำลัง 3
ตัวอย่าง: 153 = 1³+5³+3³, 370 = 3³+7³+0³, 371 = 3³+7³+1³, 407 = 4³+0³+7³
ตัวอย่าง Input และ Output
Input:
The two inputs : 1 and 500
Output:
The Armstrong numbers are: 153 370 371 407
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร my_low, my_high, i ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น ขั้นตอนที่ 4 - สร้างฟังก์ชัน IsArmstrong รับ int คืน boolean ขั้นตอนที่ 5 - ในฟังก์ชัน: แยกแต่ละหลักด้วย %10, /10 ยกกำลัง 3 รวมกันเปรียบเทียบกับต้นฉบับ ขั้นตอนที่ 6 - วนลูป for จาก my_low ถึง my_high เรียก IsArmstrong ถ้า true พิมพ์เลขนั้น ขั้นตอนที่ 7 - แสดงผลลัพธ์ ขั้นตอนที่ 8 - หยุด
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class ArmstrongNumbers {
public static void main(String[] args) {
int my_low, my_high, i;
Scanner my_scanner = new Scanner(System.in);
System.out.println("Required packages have been imported");
System.out.println("A scanner object has been defined");
System.out.println("Enter the first number :");
my_low = my_scanner.nextInt();
System.out.println("Enter the limit :");
my_high = my_scanner.nextInt();
System.out.println("The Armstrong numbers are :");
for (i = my_low + 1; i < my_high; ++i) {
if (IsArmstrong(i))
System.out.print(i + " ");
}
}
public static boolean IsArmstrong(int i) {
int check, my_rem, my_sum;
my_sum = 0;
check = i;
while (check != 0) {
my_rem = check % 10;
my_sum = my_sum + (my_rem * my_rem * my_rem);
check = check / 10;
}
if (my_sum == i)
return true;
return false;
}
}
Output
Required packages have been imported A scanner object has been defined Enter the first number : 1 Enter the limit : 500 The Armstrong numbers are : 153 370 371 407
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class ArmstrongNumbers {
public static void main(String[] args) {
int my_low, my_high, i;
my_low = 1;
my_high = 500;
System.out.println("The starting and ending numbers are defined as " + my_low + " and " + my_high);
System.out.println("The Armstrong numbers are :");
for (i = my_low + 1; i < my_high; ++i) {
if (IsArmstrong(i))
System.out.print(i + " ");
}
}
public static boolean IsArmstrong(int i) {
int check, my_rem, my_sum;
my_sum = 0;
check = i;
while (check != 0) {
my_rem = check % 10;
my_sum = my_sum + (my_rem * my_rem * my_rem);
check = check / 10;
}
if (my_sum == i)
return true;
return false;
}
}
Output
The starting and ending numbers are defined as 1 and 500 The Armstrong numbers are : 153 370 371 407