ในบทความนี้ เราจะเรียนรู้วิธีตรวจสอบว่าเลขใดเป็น Neon Number ในภาษา Java Neon Number คือเลขที่ผลรวมของหลักในกำลังสองของมันเท่ากับตัวเลขเดิม
ตัวอย่าง
9² = 81 → 8 + 1 = 9 ✓ เป็น Neon Number
1² = 1 → 1 = 1 ✓ เป็น Neon Number
ตัวอย่างการทำงาน
อินพุต:
9
เอาต์พุต:
The given input is a neon number
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร:
my_input, input_square, sum = 0 - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- คำนวณกำลังสอง:
input_square = my_input * my_input - ใช้ลูป
whileหาผลรวมหลักของ input_square - เปรียบเทียบ sum กับ my_input
- แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class NeonNumbers {
public static void main(String[] args) {
int my_input, input_square, sum = 0;
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 number: ");
my_input = my_scanner.nextInt();
input_square = my_input * my_input;
while (input_square > 0) {
sum = sum + input_square % 10;
input_square = input_square / 10;
}
if (sum != my_input) {
System.out.println("The given input is not a Neon number.");
} else {
System.out.println("The given input is Neon number.");
}
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class NeonNumbers {
public static void main(String[] args) {
int my_input = 9, input_square, sum = 0;
System.out.printf("The number is %d ", my_input);
input_square = my_input * my_input;
while (input_square > 0) {
sum = sum + input_square % 10;
input_square = input_square / 10;
}
if (sum != my_input) {
System.out.println("\nThe given input is not a Neon number.");
} else {
System.out.println("\nThe given input is Neon number.");
}
}
}
Neon Numbers ที่รู้จัก
มีเพียง 3 ตัวเท่านั้นในจำนวนเต็มบวก: 0, 1, 9
- 0² = 0 → 0 = 0
- 1² = 1 → 1 = 1
- 9² = 81 → 8 + 1 = 9