PAT-B 1007. 素数对猜想(C++, python)

python的最后一个测试点超时,跪了。难道要用转载的那个快速线性筛法求素数吗 ...


AC的C++代码:

#include <cmath>
#include <iostream>

using namespace std;

inline bool is_prime(int num)
{
	for (int i = 2; i <= sqrt(num); ++ i)
	{
		if (num % i == 0)
		{
			return false;
		}
	}
	return true;
}

int main()
{
	int n, prev = 2, cnt = 0;

	cin >> n; 
	for (int i = 2; i <= n; ++ i)
	{
		if (is_prime(i) == true)
		{
			if (i - prev == 2)
			{
				++ cnt;
			}
			prev = i;
		}
	}
	cout << cnt;

	return 0;
}

python:

import math

def is_prime(num) :
    i = 2
    cnt = int(math.sqrt(num))
    while i <= cnt:
        if num % i == 0 :
            return False
        i = i + 1        
    return True
        
if __name__ == "__main__" :
    n = input()
    prev = i = 2
    cnt = 0
    while i <= n :
        if is_prime(i) :
            if  i - prev == 2 :
                cnt = cnt + 1
            prev = i
        i = i + 1
    print cnt


你可能感兴趣的:(素数,python,Prime,PAT-B)