在一次面试中,我被问到所有的数字都只能被3,5和7整除。
if (num%3==0 || num%5==0 || num%7==0)
return true
else
return false. 但在这种情况下,如果我们有6,它将通过测试,但它也可以除以2,所以这是行不通的。你能用点什么吗?我正在使用java。查找平均值以检查某个数字是否只能被该数字整除。
发布于 2015-02-26 14:00:44
我将通过从原始数字中删除3、5和7的所有因子来处理这个问题,然后看看剩下的是什么。
while(num % 3 == 0)
{
num = num / 3;
}
while(num % 5 == 0)
{
num = num / 5;
}
while(num % 7 == 0)
{
num = num / 7;
}
return (num == 1);发布于 2015-02-26 13:52:49
我不会给您一个Java算法,因为它应该很容易实现。
你可以只是:
1. check if (n%3 == 0)
2. if it is, set n /= 3 and repeat step 1.
3. do the same for the number 5 and 7
4. now if n != 1, return false, else return true在Java算法中:
// n is some random natural number
if (n == 1 || n == 0)
return false
while (!n%3)
{
n /= 3;
}
while (!n%5)
{
n /= 5;
}
while (!n%7)
{
n /= 7;
}
if (n == 1)
{
return true;
}
else
{
return false;
}这不是最好的语法,我只是给出上述算法的直接实现。
https://stackoverflow.com/questions/28743806
复制相似问题