检查一个号码是否是 Humble
static boolean isPrime(int n)
{
if(n<=1) return false;
if(n==2) return true;
if(n%2==0) return false;
int m = (int)Math.round(Math.sqrt(n));
for(int i=3; i <= m; i+=2)
if(n%i==0)
return false;
return true;
}
static boolean isHumble(int n)
{
for(int i = 2; i <= n; i++)
{
if (isPrime(i) && isFactor(n, i))
{
System.out.println(i);
//if(isPresent(i))
// return false;
//else return true;
return true;
}
}
return false;
}
static boolean isFactor(int val1, int val2)
{
return val1%val2==0;
}
static boolean isPresent(int n){
for(int val : prime_factors)
if(n==val)
return true;
return false;
}
// prime_factors {2,3,5,7}
我正在实现 isHumble 函数,但由于某种原因似乎有些问题。有人可以帮我吗?
static boolean isPrime(int n)
{
if(n<=1) return false;
if(n==2) return true;
if(n%2==0) return false;
int m = (int)Math.round(Math.sqrt(n));
for(int i=3; i <= m; i+=2)
if(n%i==0)
return false;
return true;
}
static boolean isHumble(int n)
{
for(int i = 2; i <= n; i++)
{
if (isPrime(i) && isFactor(n, i))
{
System.out.println(i);
//if(isPresent(i))
// return false;
//else return true;
return true;
}
}
return false;
}
static boolean isFactor(int val1, int val2)
{
return val1%val2==0;
}
static boolean isPresent(int n){
for(int val : prime_factors)
if(n==val)
return true;
return false;
}
// prime_factors {2,3,5,7}
I am implementing an isHumble function, but for some reason something seems to be off. Can anyone help me out please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑
将 1 添加到您的素数列表中,然后尝试以下操作:
以便将这些因数从该数字中删除,并且以后不会再找到。
编辑 2
一个更简单的解决方案是:
Edit
Add 1 to your list of prime numbers, and try the following:
So that those factors are removed from the number and not found later.
Edit 2
A simpler solution would be:
正如它所写的,由于
isFactor
方法的编写方式,您的isHumble
方法将为每个数字返回 false...As it's written your
isHumble
method will return false for every number because of the way yourisFactor
method is written...一个不起眼的数字是唯一质因数为 2、3、5、7 的数字。这意味着,如果你取 0 到 n/2 之间的所有“素数”,那么只有 2,3,5,7 可以整除它们。
相反,您将取 0 到 n/2 之间的所有数字并检查它们是否是因子。
因此,在你的情况下,当 i=9 时,语句
if(n%i == 0) 返回 true,因此 return false 正在执行。
在 i 上仅运行素数而不是从 0 到 n/2 的所有数字,你应该没问题。
A humble number is one whose only prime factors are 2,3,5,7. That means, if you take all the "prime numbers" from 0 to n/2, only 2,3,5,7 should divide them.
Instead you are taking all the numbers from 0 to n/2 and checking whether they are factors.
Hence in your case when i=9, the statement
if(n%i == 0) returns to true and hence return false is getting executed.
Run your outer loop on i for only prime numbers instead of all the numbers from 0 to n/2 and you should be fine.
您的
isFactor
方法可以更容易地编写为Your
isFactor
method could be easier be written as