020-29133788
    资 讯
    您的位置:首页 >> 资 讯 >> 软件应用 >> 编程开发 >> 正文
    双生质数

    点击:   发布日期:2013-01-20

    本文来自 www.020fix.com


    若N是质数,且N+2也是质数,则称为【双生质数】。
    请写一C程式,输入a b两数字,输出a、b之间的双生质数,直到输入-1为止。
    复制内容到剪贴板
    代码:
    #include <stdio.h>

    void main( ){

            int *simPrime;
            int N, count=0, step, low, up, num_twin_primes;
           
            while ( 1 ){

                    scanf("%d", &low);
                    if ( low == -1 )
                            return;
                    scanf("%d", &up);  

                    num_twin_primes = 0;

                    N = (up-3)/2;
                    simPrime = (int*)malloc(sizeof(int)*N);

                    for(int i=0; i<N; i++)
                            simPrime[i]=0;
                                                       
                    for(i=0; i<N; i++)
                            if(simPrime[i]==0) {
                                    step = 2*i+3;
                                    count++;
                                    for(int k=step+i; k<N; k+=step)
                                            simPrime[k]=1;
                            }

                    for(i=(low-3)/2; i<N-1; i++)
                            if(simPrime[i]==0 && simPrime[i+1]==0){
                                    printf("%d\t%d\n", 2*i+3, 2*i+5);
                                    num_twin_primes++;
                            }

                    if ( num_twin_primes == 0 )
                            printf("此范围内无双生质数\n");

                    for ( i=0; i<10; i++ )
                            printf("=");
                    printf("\n");

                    free(simPrime);
            }
    }