首页 > 解决方案 > C程序计算范围内素数之间的最大差距

问题描述

谁能帮我写这个程序?即使是伪代码也可以完成这项工作。这个程序应该扫描一个像 34 这样的数字并计算 34 之前素数之间的最大差距,我的意思是 (29-23-1)=5。太感谢了

int y,x,N,large=3,small=2,b,a;

scanf("%d",&N);

    for(y=3;y<N;++y)
        for(x=2;x<y;++x)
            a=y%x;

    if(a==0) break;

    else if(y>large && y>small) small=large;

    large=y;small=x;b=large-small-1;

    if(b<large-small-1)b=large-small-1;

    printf("%d",b);

标签: cprimes

解决方案


谁能帮我写这个程序?

嗯,这是一个明确而具体的问题。但是,我不会回答“是”,而是会展示您的尝试所需的小重新排列,并在评论中进行解释。

#include <stdio.h>

main()
{
    int y, x, N, large=2, small, b=0, a;    // don't forget to initialize b
    scanf("%d", &N);
    for (y=3; y<N; ++y)
        for (x=2; x<y; ++x)
        {
            a=y%x;
            if (a==0) break;

            if (x*x < y) continue;      // continue if unsure whether y is prime

            small=large;
            large=y;
            if (b<large-small)
                b=large-small;
            break;                      // we handled this prime y, go to next y
        }
    printf("%d\n", b);
}

推荐阅读