PAT: 1007 for prime conjecture (c language version)

Let us define D
n-
as: D
n-
= P
n-+. 1
-p
n-
, where P
i
is the i-th prime number. Clearly D
. 1
=. 1, and for n> 1 with a D
n-
is an even number. "Primes to guess" that "there is an infinite number of adjacent and poor is a prime number 2."

Now given an arbitrary positive integer N (<10
. 5
), does not exceed Calculate number N satisfies the conjecture of primes.

Input formats:
on a single line is given positive integer N.

Output Format:
Output of the number of prime numbers is not more than N satisfies a conjecture in a row.

Sample input:
20

Sample output:
4

The first method: First find all prime numbers and then compare

#include <stdio.h>

const int difference = 2;

int isPrime(int n);

int main()
{
    int i, k, n, len, count = 0;
    int a[100000];     //开的过小也可能会由点过不去

    scanf("%d", &n);
    for (k = 0, i = 2; i <= n; i++)   //不超过n,不要忘记等于号,否则会有一个点过不去
        if (isPrime(i))
            a[k++] = i;
    len = --k;
    for (i = 0; i < len; i++)
    {
        if (a[i + 1] - a[i] == difference)
            count++;
    }
    printf("%d", count);

    return 0;
}

int isPrime(int n)
{
    int i;

    if (n <= 1)
        return 0;
    for (i = 2; i * i <= n; i++)
        if (n % i == 0)
            return 0;

    return 1;
}

The second method while looking for side comparison

To be added//

Published 24 original articles · won praise 0 · Views 148

Guess you like

Origin blog.csdn.net/qq_45624989/article/details/105106409