Skip to content

Instantly share code, notes, and snippets.

@sighingnow
Created October 1, 2016 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sighingnow/217369a835e314f7f602177797cade49 to your computer and use it in GitHub Desktop.
Save sighingnow/217369a835e314f7f602177797cade49 to your computer and use it in GitHub Desktop.
Summary of all prime numbers less than or equal to n.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from time import time
import math
def prime_sum_impl(n):
r = int(math.sqrt(n))
v = [n//i for i in range(1, r+1)]
v += list(range(v[-1]-1, 0, -1))
s = {i:(2+i)*(i-1)//2 for i in v}
for p in range(2, r+1):
if not s[p] > s[p-1]:
continue
for k in v:
if k < p*p:
break
else:
s[k] -= p*(s[k//p] - s[p-1])
return s[n]
def prime_sum(n):
t = time()
return prime_sum_impl(n), time()-t
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize(
"prime_sum.py",
compiler_directives = {
'boundscheck': False,
'wraparound': True,
'initializedcheck': False,
'nonecheck': False,
'overflowcheck': False,
'overflowcheck.fold': False,
'embedsignature': False,
'cdivision': True,
'cdivision_warnings': False,
'linetrace': False,
'infer_types': True,
'unraisable_tracebacks': False,
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment