查找两个值之间的孪生素数
Finding twin primes between two values
我被这个问题困扰了好久,似乎不知道如何完成这个程序。我是编程初学者,所以我只知道 C。我承认这是一项作业,我不是在寻找答案,但我真的很感激能为这个问题提供一点帮助。这是我的:
#include <stdio.h>
#include <math.h>
void main()
{
int low, high, n, count,i;
scanf ("%d %d",&low, &high);
count=0;
n=0;
if (low<=3)
count=count+1;
while (n<low)
{
n=n+6;
}
while (n<high)
{
i=1;
while (i<sqrt(n+1))
{
i=i+2;
if ((n-1)%i==0 || (n+1)%i==0)
continue;
else
count=count+1;
}
n=n+6;
}
printf("the number of twin primes between %d and %d are %d",low, high, count);
}
我是否使用了 while
循环错误的 and/or if
语句?我没有被教导使用 for 循环,所以我不能使用它们。我还必须使用这样一个事实,即除了 {3,5}
之外的每个孪生素数都遵循公式 6+/-1.
谢谢你帮助我。
以下程序可以正常工作。
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
int low, high, n, count, i;
scanf ("%d %d", &low, &high);
count = 0;
n = 0;
if (low <= 3)
count++;
while (n<low)
n += 6;
while (n < high) {
i = 1;
int flag = 0;
while (i * i < n + 1) {
i++;
if ((n - 1) % i == 0 || (n + 1) % i == 0)
flag = 1;
}
if (!flag)
count++;
n += 6;
}
printf("the number of twin primes between %d and %d are %d", low, high, count);
}
如您所见,您只需要在主要检测阶段使用诸如标志之类的东西。
我被这个问题困扰了好久,似乎不知道如何完成这个程序。我是编程初学者,所以我只知道 C。我承认这是一项作业,我不是在寻找答案,但我真的很感激能为这个问题提供一点帮助。这是我的:
#include <stdio.h>
#include <math.h>
void main()
{
int low, high, n, count,i;
scanf ("%d %d",&low, &high);
count=0;
n=0;
if (low<=3)
count=count+1;
while (n<low)
{
n=n+6;
}
while (n<high)
{
i=1;
while (i<sqrt(n+1))
{
i=i+2;
if ((n-1)%i==0 || (n+1)%i==0)
continue;
else
count=count+1;
}
n=n+6;
}
printf("the number of twin primes between %d and %d are %d",low, high, count);
}
我是否使用了 while
循环错误的 and/or if
语句?我没有被教导使用 for 循环,所以我不能使用它们。我还必须使用这样一个事实,即除了 {3,5}
之外的每个孪生素数都遵循公式 6+/-1.
谢谢你帮助我。
以下程序可以正常工作。
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
int low, high, n, count, i;
scanf ("%d %d", &low, &high);
count = 0;
n = 0;
if (low <= 3)
count++;
while (n<low)
n += 6;
while (n < high) {
i = 1;
int flag = 0;
while (i * i < n + 1) {
i++;
if ((n - 1) % i == 0 || (n + 1) % i == 0)
flag = 1;
}
if (!flag)
count++;
n += 6;
}
printf("the number of twin primes between %d and %d are %d", low, high, count);
}
如您所见,您只需要在主要检测阶段使用诸如标志之类的东西。