如何在Java中檢查一個數是否為陽光數?
如果一個數的下一個值的平方根是任何數的完全平方數,則稱該數為陽光數。
為了更清楚地說明,如果我們將 1 加到任何數上,我們就會得到下一個值。然後我們必須找出它的平方根。如果我們得到任何整數,那麼我們可以說它是任何數的完全平方數。如果我們確認下一個數有一個完全平方數,那麼輸入的數就是陽光數,否則就不是陽光數。
在這篇文章中,我們將瞭解如何使用 Java 程式語言檢查一個數是否為陽光數。
舉幾個例子
示例 1
輸入數字為 80。
讓我們使用陽光數的邏輯來檢查它。
80 的下一個值為 80 + 1 = 81
81 的平方根 = 9
正如我們在這裡看到的,81 是 9 的完全平方數。
因此,80 是一個陽光數。
示例 2
輸入數字為 48。
讓我們使用陽光數的邏輯來檢查它。
48 的下一個值為 48 + 1 = 49
49 的平方根 = 7
正如我們在這裡看到的,49 是 7 的完全平方數。
因此,48 是一個陽光數。
示例 3
輸入數字為 122。
讓我們使用陽光數的邏輯來檢查它。
122 的下一個值為 122 + 1 = 123
123 的平方根 = 11.09053651
正如我們在這裡看到的,123 不是完全平方數。
因此,122 不是陽光數。
其他一些陽光數的例子包括 3、8、15、24、35、48、63 等。
語法
要獲得一個數的平方根,我們在 **java.lang** 包的 **Math** 類中有一個內建的 **sqrt()** 方法。
以下是使用該方法獲取任何數的平方根的語法。
double squareRoot = Math.sqrt(input_vale)
您可以使用 **Math.floor()** 查詢最接近的整數。
Math.floor(square_root)
演算法
**步驟 1** - 透過初始化或使用者輸入獲取一個整數。
**步驟 2** - 然後我們透過向其新增 1 來找到它的下一個值,並將其儲存在另一個變數中。
**步驟 3** - 我們找到下一個值的平方根。
**步驟 4** - 現在我們找到最接近的完全平方根,並用下一個值的平方根減去它。
**步驟 5** - 如果減法後的值為零,那麼我們將得到確認,它是一個整數,表明下一個值是任何數的完全平方數。
**步驟 6** - 如果我們得到確認,下一個數是完全平方數,則列印該數是陽光數,否則它不是陽光數。
多種方法
我們提供了不同方法的解決方案。
使用靜態輸入值
使用使用者定義的方法
讓我們逐一檢視程式及其輸出。
方法 1:使用靜態輸入值
在這種方法中,一個整數值將在程式中初始化,然後使用演算法檢查該數是否為陽光數。
示例
import java.util.*; public class Main{ public static void main(String args[]){ //declare an int variable and initialize with a static value int inputNumber=8; //declare a variable which store next value of input number double next=inputNumber + 1; //Find the square root of the next number //store it as double value double square_root = Math.sqrt(next); //check whether the square root is a integer value or not //if yes return true otherwise false if(((square_root - Math.floor(square_root)) == 0)) //if true then print it is a sunny number System.out.println(inputNumber + " is a sunny number."); else //if true then print it is a sunny number System.out.println(inputNumber + " is not a sunny number."); } }
輸出
8 is not a sunny number.
方法 2:使用使用者定義的方法
在這種方法中,我們將一個靜態值作為輸入數字,並將此數字作為引數傳遞給使用者定義的方法,然後在方法內部使用演算法檢查該數字是否為陽光數。
示例
import java.util.*; public class Main{ public static void main(String args[]){ //declare an int variable and initialize with a static value int inp=15; //call the user defined method inside the conditional statement if(checkSunny(inp)) //if true then print it is a sunny number System.out.println(inp + " is a sunny number."); else //if true then print it is a sunny number System.out.println(" is not a sunny number."); } //define the user defined method static boolean checkSunny(int inputNumber){ //declare a variable which store next value of input number double next=inputNumber + 1; //Find the square root of the next number // store it as double value double square_root = Math.sqrt(next); //check whether the square root is a integer value or not //if yes return true otherwise false return ((square_root - Math.floor(square_root)) == 0); } }
輸出
15 is a sunny number.
在本文中,我們探討了如何使用三種不同的方法在 Java 中檢查一個數是否為陽光數。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP