Java 如何判断一个数是否是丑数
如果一个数的质因数只包括2、3和5,那么它就被称为 丑数 。
也许有些数有一些质因数只有一个因子或两个因子,但这些因子必须是2、3和5之一。
在本文中,我们将看到如何使用Java编程语言来判断一个数是不是 丑数 。
为了给你展示一些实例
实例1
输入的数为20。
让我们通过使用丑数的逻辑来检查一下。
Prime factors of 20 = 2, 2, 5
因此,注意到这里的所有质因数只包含2、3和5中的一个。
因此,20是一个丑数。
示例2
输入数字为30。
让我们用丑数的逻辑来检查它。
Prime factors of 30 = 2, 3, 5
所以,你可以注意到,所有的质因数只包含2、3和5中的任意一个。
因此,30是一个丑数。
实例3
输入数字是14。
让我们用丑数的逻辑来检查它。
Prime factors of 14 = 2, 7
所以,如您在上面所注意到的,7出现在其中一个质因数中。
因此,14不是一个丑数。
步骤
- 步骤1 - 首先我们定义一个函数来检查输入的数字是否是一个质数。
-
步骤2 - 通过静态方式或用户定义的方法从用户那里收集输入。
-
步骤3 - 初始化循环以找到输入数字的所有质因数。
-
步骤4 - 在找到质因数之后,运行一个条件来检查因子是否只包括2、3和5。
-
步骤5 - 如果条件为真,则打印输入数字是一个丑数,否则输入数字不是一个丑数。
多种方法
我们提供了不同的解决方案。
- 通过使用静态输入值
-
通过使用用户定义的方法
让我们逐个查看Java程序及其输出。
方法1:通过使用静态输入值
在这种方法中,程序中将初始化一个非零的正整数值,然后使用算法来检查一个数字是否是一个丑数。
示例
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
//declare a variable with a static value
int inputNumber = 25;
//declare a variable with boolean value
boolean check = true;
//initialise the loop for the checking of ugly number
for(int i = 2; i<=inputNumber; i++) {
// checks whether numbers only include 2,3 and 5
if(i!=2&&i!=3&&i!=5) {
// Checks if there are some other prime factors
if(inputNumber%i==0&&checkPrime(i)) {
// Sets the flag to false if there are some other prime factors
check = false;
break;
}
}
}
if(check) {
System.out.println(inputNumber+" is an ugly number");
} else {
System.out.println(inputNumber+" is Not an ugly number");
}
}
// Function that checks for prime
static boolean checkPrime(int number) {
boolean flag = true;
for(int i = 2; i<=number/2; i++) {
if(number%i==0) {
flag = false;
break;
}
}
return flag;
}
}
输出
25 is an ugly number
方法2:使用用户定义的方法
在这种方法中,程序中将初始化一个非零的正整数值,然后我们将通过将此输入数字作为参数来调用一个用户定义的方法。
在方法内部,我们将使用该算法来检查一个数字是否为 丑数 。
示例
import java.util.Scanner;
public class Main {
//initialise main method
public static void main(String[] args) {
//declare a variable with a static value
int inp = 56;
//check whether our condition is true or not in user defined method
//if true number is ugly otherwise not
if(checkUgly(inp)) {
System.out.println(inp+" is an ugly number");
} else {
System.out.println(inp+" is Not an ugly number");
}
}
// Function that checks for prime
static boolean checkPrime(int number) {
boolean flag = true;
for(int i = 2; i<=number/2; i++) {
if(number%i==0) {
flag = false;
break;
}
}
return flag;
}
//define the user defined method
//checking for ugly number
public static boolean checkUgly(int inputNumber) {
//declare a variable with boolean value
boolean check = true;
//initialise the loop for the checking of Ugly number
for(int i = 2; i<=inputNumber; i++) {
// checks whether numbers only include 2,3 and 5
if(i!=2&&i!=3&&i!=5) {
// Checks if there are some other prime factors
if(inputNumber%i==0&&checkPrime(i)) {
// Sets the flag to false if there are some other prime factors
return false;
}
}
}
return true;
}
}
输出
56 is Not an ugly number
在这篇文章中,我们通过使用不同的方法,探讨了如何检查一个数字是否是丑数。