如何在Java中检查一个数字是否是丑数?

2023年 8月 28日 51.0k 0

如何在Java中检查一个数字是否是丑数?

如果一个数的质因数只包括2、3和5,那么它被称为丑数。

也许某些数字具有仅有一个或两个因子的质因数,但这些因子必须是2、3和5之一。

In this article we will see how to check if a number is an Ugly number or not by using Java programming language.

To show you some instances

Instance-1

Input number is 20.

让我们使用丑数的逻辑来检查一下。

Prime factors of 20 = 2, 2, 5

登录后复制

所以,正如你在这里注意到的,所有的质因数只包括2、3和5中的任意一个。

Hence, 20 is an ugly number.

Instance-2

Input number is 30.

让我们使用丑数的逻辑来检查一下。

Prime factors of 30 = 2, 3, 5

登录后复制

所以,正如你在这里注意到的,所有的质因数只包括2、3和5中的任意一个。

Hence, 30 is an ugly number.

Instance-3

Input number is 14.

让我们使用丑数的逻辑来检查一下。

Prime factors of 14 = 2, 7

登录后复制

So, as you notice here 7 is present at one of the prime factors above.

Hence, 14 is not an ugly number.

Algorithm

  • Step 1 − First we define a function for checking if the input number is a prime number or not.

  • 步骤2 - 通过静态方法或用户定义的方法收集用户的输入。

  • 步骤 3 − 初始化循环以找到输入数字的所有质因数。

  • 第4步 - 找到质因数后,我们运行一个条件来检查因子是否只包含2、3和5。

  • Step 5 − If the condition is true then we are printing the input number is an ugly number otherwise the input number is not an ugly number.

Multiple Approaches

我们以不同的方法提供了解决方案。

  • 通过使用静态输入值

  • By Using User Defined Method

让我们逐一查看Java程序及其输出。

Approach-1: By Using Static Input Value

In this approach one non−zero, positive integer value will be initialized in the program and then by using the algorithm we can check whether a number is an ugly number or not.

Example

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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论