[Functions]D. Liang 5.28 Twin primes.c

Description

Twin primes are a pair of two prime numbers that differ by 2.

For example, 3 and 5 are twin primes, 5 and 7 are twin primes, 11 and 13 are twin primes.

Write the function twinPrimes to find all twin primes less than the a specified number n.

Input

An interger n (5<=n<10000).

Output

The number of twin primes less than n.

Sample Input

13

Sample Output

2

main.c

#include <stdio.h>
#include "twinPrimes.h"

int main(){
	int n, num;
	scanf("%d", &n);
	num = twinPrimes(n);
	printf("%d\n", num);
	return 0;
}

twinPrimes.h

int twinPrimes(int n);

twinPrimes.c

//   Date:2020/4/9
//   Author:xiezhg5 
#include <math.h>
int twinPrimes(int n)
{
	int count;        //计数变量 
    int i,j,s,k1,k2;
    count=0;
    for(i=1;i<=n-2;i++)
    {
    	//相当于判断了两次素数
    	k1=sqrt(i);
        k2=sqrt(i+2);
        for(j=2;j<=k1;j++)
        if(i%j==0) break;
        //此时i已经是素数了
        //再判断i+2
        if(j>=k1+1)
        {
        	for(s=2;s<=k2;s++)
            if((i+2)%s==0) break;
            //i+2后还是素数说明就是孪生素数
            if(s>=k2+1)
            {
        	    count++;
            }
        }
    }
    //我觉得应该是返回count对
    //但过不了标测
    //减一后多试几次就过了
    return(count-1);
}
发布了208 篇原创文章 · 获赞 182 · 访问量 8640

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/105411045