gpt4 book ai didi

java - Java 中重要因素的数量

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:14 24 4
gpt4 key购买 nike

我有一个问题要检查总计数是否等于数字的任何因子。我正处于 JAVA 编程的学习阶段。问题如下:

*

A Bishal number is a number such that the number of nontrivial factors is a factor of the number. For example, 6 is a Bishal number because 6 has two nontrivial factors : 2 and 3. (A nontrivial factor is a factor other than 1 and the number). Thus 6 has two nontrivial factors. Now, 2 is a factor of 6. Thus the number of nontrivial factors is a factor of 6. Hence 6 is a Bishal number. Another Bishal number is 30because 30 has 2, 3, 5, 6, 10, 15 as nontrivial factors. Thus 30 has 6 nontrivial factors. Note that 6 is a factor of 30. So 30 is a Bishal Number. However 21 is not a Bishal number. The nontrivial factors of 21 are 3 and 7. Thus the number of nontrivial factors is 2. Note that 2 is not a factor of 21. Therefore, 21 is not a Bishal number. Write a function named isBishal that returns 1 if its integer argument is a Bishal number, otherwise it returns 0.
The signature of the function is int isBishal(int n)

*

我可以创建一个函数。但我不知道如何用因素检查总数。我的部分解决方案如下:

public static int isBishal(int n){
int count=0; //for number of factor of entered number n
for (int i=2; i<n; i++){ //for excluding 1 and itself in factors list
double result=(double)n/i;
if(result==Math.ceil(result)){
int factor=(int) result; //to check factor(one can use reminder 0 case)
count++;
} //closing if clause
} //closing for loop

我在哪里可以将最终计数(即因子总数)与任何因子进行比较?如果我使用 factor equals 来计数,则计数从 1、2、3 开始,依此类推。它可能会将计数 1 、 2,3 等与因子进行比较。我需要比较最终计数。所以我已经把计数排除在外了。但是 factor 的范围就在 if 子句之内。不能在循环外比较。

任何人都可以在这个程序中让我清楚。P.S:这个程序不完整,因为我无法比较。

最佳答案

您必须存储找到的因子,以便检查非平凡因子的数量是否是一个因子。

例如,您可以使用 HashSet :

public static boolean isBishal(int n) { // I changed the return type to boolean
int count=0;
Set<Integer> factors = new HashSet<>();
for (int i=2; i<n; i++){
if (n % i == 0) { // note this is a simpler way to check if i is a factor of n
factors.add(i);
count++;
}
}
return factors.contains(count);
}

编辑:正如 khelwood 所建议的,另一种存储因子的方法是在循环结束时检查 count 是否是 n 的一个因子:

public static boolean isBishal(int n) { 
int count=0;
for (int i=2; i<n; i++){
if (n % i == 0) {
count++;
}
}
return (count > 1) && (n % count == 0);
}

关于java - Java 中重要因素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com