PAT (Basic Level) 1007 素数对猜想

PAT (Basic Level) 1007 素数对猜想_第1张图片

C语言(18分):

#include 
int isPrime(int num) {
    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return 0;
        }
    }
    return 1;
}
int main()
{
    int N;
    scanf("%d", &N);
    int count = 0;
    int temp = 2;
    for (int i = 2; i <= N; i++) {
        if (isPrime(i)) {
            if (i - temp == 2) {
                count++;
            }
            temp = i;
        }
    }
    printf("%d", count);
    return 0;
}

Java语言(18分):

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int count = 0;
        int temp = 2;
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                if (i - temp == 2) {
                    count++;
                }
                temp = i;
            }
        }
        System.out.print(count);
    }

    public static boolean isPrime(int num) {
        for (int i = 2; i <= num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:(PAT (Basic Level) 1007 素数对猜想)