我想写一个非常简单的主要应用程序。但是我在下面的代码中遇到了一些问题,它应该从0到99生成素数。但它只是显示99.
一个问题是只显示最后一个数字。但另一个是主要的“检查”不起作用。我该如何解决这些问题。
for (i=0; i<100; i++) {
for (n=2; n<i; n++) {
if (i%n == 0) break;
else primetext.text = [NSString stringWithFormat:@"%i, ", i];
}
}
答案 0 :(得分:2)
您应该将数字附加到primetext.text而不是分配。现在它正在每次迭代时被重新分配。
答案 1 :(得分:2)
有很多问题,我会尝试解释它们
i+=2
加倍你的速度以下是您修改这些要点的方法。
int maxNum = 100;
primetext.text = @"2 "; //Start knowing that 2 is the lowest prime (avoid evaluating evens)
for (i=3; i<=maxNum; i+=2) //Start at 3 and add 2 (avoid 1 and 2 as well as even numbers)
{
bool isPrime = YES; //Assume that i is prime
for (n=2; n<sqrt(i); n++) //Divide by every number up to square root
{
if (i%n == 0) //If evenly divisible by n, not a prime
{
isPrime = NO;
break; //Don't need to check any more factors, so break
}
}
if (isPrime) //If isPrime was never set to NO, i is prime
{
NSString *temp = [NSString stringWithFormat:@"%d ", i];
primetext.text = [primetext.text stringByAppendingString:temp];
}
}
希望这有帮助。