Instantly share code, notes, and snippets.

# sighingnow/prime_sum.py

Created October 1, 2016 04:56
Show Gist options
• Save sighingnow/217369a835e314f7f602177797cade49 to your computer and use it in GitHub Desktop.
Summary of all prime numbers less than or equal to n.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 #! /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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 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, }) )