Last active
January 29, 2016 02:41
-
-
Save inaz2/223aa8c2cdf73462dc0c to your computer and use it in GitHub Desktop.
Using C function from Python ctypes
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
$ gcc -shared -fPIC trial_division.c -o trial_division.so | |
$ time python uselib.py | |
14115591195084627607 | |
14115591195084627607 = 3667917713 * 3848393639 | |
real 0m30.045s | |
user 0m30.008s | |
sys 0m0.012s |
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
typedef unsigned long long ulonglong; | |
ulonglong trial_division(ulonglong n) | |
{ | |
ulonglong i; | |
if (n % 2 == 0) return 2; | |
if (n % 3 == 0) return 3; | |
for (i=6; (i-1)*(i-1)<=n; i+=6) { | |
if (n % (i-1) == 0) return (i-1); | |
if (n % (i+1) == 0) return (i+1); | |
} | |
return 1; | |
} |
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 ctypes import * | |
n = 0xc3e4a76781a69e97 | |
lib = CDLL('./trial_division.so') | |
lib.trial_division.argtypes = [c_ulonglong] | |
lib.trial_division.restype = c_ulonglong | |
p = lib.trial_division(n) | |
q = n // p | |
print n | |
print "%d = %d * %d" % (p*q, p, q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment