Java 如何检查一个数是否是阳光数
如果输入数的下一个值的平方根是任何数的完全平方数,则称该数为阳光数。
为了更清楚,我们可以将任何数加一得到下一个值,并找出其平方根。如果我们得到任何整数值,那么我们可以说它是任何一个数的完全平方数。如果我们确认下一个数有一个完全平方数,那么输入数就是一个阳光数,否则它不是一个阳光数。 文章中我们将看到如何通过使用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.
在本文中,我们探讨了如何通过使用三种不同的方法来检查一个数字是否为阳数。