gmp.py 1004 B

123456789101112131415161718192021222324252627282930313233
  1. import sys
  2. #
  3. # This is only a demo based on the GMP library.
  4. # There is a rather more complete (but perhaps outdated) version available at:
  5. # http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
  6. #
  7. try:
  8. from _gmp_cffi import ffi, lib
  9. except ImportError:
  10. print 'run gmp_build first, then make sure the shared object is on sys.path'
  11. sys.exit(1)
  12. # ffi "knows" about the declared variables and functions from the
  13. # cdef parts of the module created from gmp_build
  14. # lib "knows" how to call the functions from the set_source parts
  15. # of the module.
  16. # ____________________________________________________________
  17. a = ffi.new("mpz_t")
  18. b = ffi.new("mpz_t")
  19. if len(sys.argv) < 3:
  20. print 'call as %s bigint1, bigint2' % sys.argv[0]
  21. sys.exit(2)
  22. lib.mpz_init_set_str(a, sys.argv[1], 10) # Assume decimal integers
  23. lib.mpz_init_set_str(b, sys.argv[2], 10) # Assume decimal integers
  24. lib.mpz_add(a, a, b) # a=a+b
  25. s = lib.mpz_get_str(ffi.NULL, 10, a)
  26. print ffi.string(s)