我正在编写一个简单的算法来检查整数的原始性,我在将这个Java代码转换为Python时遇到了问题:
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
Run Code Online (Sandbox Code Playgroud)
所以,我一直在尝试使用它,但我显然正在跳过3:
i = 3
while (i < int(math.sqrt(n))):
i += 2 # where do I put this?
if (n % i == 0):
return False
Run Code Online (Sandbox Code Playgroud) private static int chain(int n){
int count = 0;
while(n > 1){
if(n % 2 == 0){
count++; //the value is not stored
return chain(n/2);
}
count++; //same thing
return chain(3*n+1);
}
return count; //prints the initial value (0)
}
}
Run Code Online (Sandbox Code Playgroud)
我需要打印链方法重新出现的次数.
作为一个新手python爱好者,我发现这非常烦人:
def isPrime(x):
if x < 0: raise Exception("The number is negative.")
if x == 0 or x == 1: return False
if x == 2: return True
else:
if x % 2 == 0: return False
for i in xrange (3, int(math.sqrt(x)), 2): #-------> This doesn't do anything.
if x % i == 0: return False # Even if I put 3 instead of i, it still prints numbers that are divisible by 3.
return True
for i in …
Run Code Online (Sandbox Code Playgroud) 假设我有这个字符串:"abcd123fx".现在,我想制作一个方法,检查(按顺序)"a","b","c","d"等是否为数字,如果不是,则返回false.我不知道如何处理char的第n个位置和每个char的顺序.