Checking if a number is 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}
I am implementing an isHumble function, but for some reason something seems to be off. Can anyone help me out please?
Edit
Add 1 to your list of prime numbers, and try the following:
boolean isHumble(int n)
{
if (isFactor(n)) return true;
for(int i=2;i<=n/2;i++)
{
while(n%i == 0)
if (isFactor(i))
n /= i;
else
return false;
}
return isFactor(n);
}
So that those factors are removed from the number and not found later.
Edit 2
A simpler solution would be:
boolean isHumble(int n)
{
for (int val : prime_factors)
while (n % val == 0) n /= val;
return (n == 1);
}
As it's written your isHumble
method will return false for every number because of the way your isFactor
method is written...
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.
Your isFactor
method could be easier be written as
boolean isFactor(int n){
return prime_factors.contains(n);
}
精彩评论