Trong bài viết này, chúng ta sẽ tìm hiểu cách kiểm tra một số có phải là số Neon hay không. Số Neon là số mà tổng các chữ số của bình phương nó bằng chính nó.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào:
9
Đầu ra
Kết quả mong đợi (vì 9² = 81, 8+1=9):
Đầu vào là số Neon
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo số nguyên my_input Bước 3 - Nhập số từ người dùng hoặc hardcode Bước 4 - Đọc giá trị Bước 5 - Tính bình phương, lưu vào input_square Bước 6 - Tính tổng các chữ số của input_square, so sánh với my_input Bước 7 - Nếu khớp, là số Neon Bước 8 - Nếu không, không phải số Neon Bước 9 - Hiển thị kết quả Bước 10 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.
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.");
}
}
Đầu ra
Required packages have been imported A scanner object has been defined Enter the number: 9 The given input is Neon number.
Ví dụ 2: Giá trị định nghĩa trước
Số đã được định nghĩa trước.
public class NeonNumbers {
public static void main(String[] args) {
int my_input, input_square, sum = 0;
my_input = 9;
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.");
}
}
Đầu ra
The number is 9 The given input is Neon number.