【问题标题】:Finding twin primes between two values查找两个值之间的孪生素数
【发布时间】:2015-04-08 01:14:37
【问题描述】:

我已经被这个问题困扰很久了,似乎不知道如何完成这个程序。我是编程初学者,所以我只知道 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 循环错误和/或 if 语句?我没有被教导使用 for 循环,所以我不能使用那些。我还必须使用除{3,5} 之外的每个孪生素数都遵循公式 6+/-1 的事实。

谢谢你帮助我。

【问题讨论】:

  • 请编辑并修正您的格式。
  • 你的问题到底是什么——程序崩溃,程序没有给出正确的结果?此外,scanf 的格式字符串看起来很“可疑”——我想你可能忘记了两个转换说明符之间的空格(%d's)
  • 现在是学习使用调试器的好时机。
  • 它没有给我正确的结果,例如,如果我输入 1 到 100 的范围,结果应该是 8,因为在给定的范围内有 8 个孪生素数。

标签: c if-statement while-loop


【解决方案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);
}

如您所见,您的主要检测阶段只需要标志之类的东西。

【讨论】:

  • 太棒了,谢谢!我只是不明白这个标志的目的,你能解释一下吗?
  • 素数(或素数)是大于 1 的自然数,除了 1 和它自身之外没有正除数,因此您必须决定何时检查所有它是除数,但您决定何时检查其中一个除数。对不起我的英语不好
  • 这个答案(和问题中)的第一个循环是while (n&lt;low) n += 6;,这是写n = low / 6; 的慢速方式,不是吗?
  • 是的,你是对的,我不想改变他的代码这么多。
猜你喜欢
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2012-01-12
  • 2014-06-26
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
相关资源
最近更新 更多