local ffi = require 'ffi' local M = ffi.load 'ssl' ffi.cdef [[ typedef struct bignum_st { uint64_t *d; int top; int dmax; int neg; int flags; } BN; typedef BN * BN_ptr; typedef const BN * BN_srcptr; BN_ptr BN_new(void); void BN_free(BN_ptr); int BN_set_word(BN_ptr, uint64_t); int BN_sub_word(BN_ptr, uint64_t); char * BN_bn2dec(BN_srcptr); void CRYPTO_free(void *, const char *, int); typedef struct bignum_pool_item { BN vals[16]; // vals[BN_CTX_POOL_SIZE]; struct bignum_pool_item *prev, *next; } BN_POOL_ITEM; typedef struct bignum_pool { BN_POOL_ITEM *head, *current, *tail; unsigned used, size; } BN_POOL; typedef struct bignum_ctx_stack { unsigned int *indexes; unsigned int depth, size; } BN_STACK; typedef struct bignum_ctx { BN_POOL pool; BN_STACK stack; unsigned int used; int err_stack; int too_many; int flags; } BN_CTX; typedef BN_CTX * BN_CTX_ptr; BN_CTX_ptr BN_CTX_new(void); void BN_CTX_free(BN_CTX_ptr); int BN_mod_mul(BN_ptr, BN_srcptr, BN_srcptr, BN_srcptr, BN_CTX_ptr); int BN_mod_exp(BN_ptr, BN_srcptr, BN_srcptr, BN_srcptr, BN_CTX_ptr); ]] function bn2str(bn) return ffi.string(ffi.gc(M.BN_bn2dec(bn),function (a) M.CRYPTO_free(a,"",0) end)) end function ul2bn(ul) local bn = ffi.gc(M.BN_new(),M.BN_free) if ul~=nil then M.BN_set_word(bn,ul) end return bn end function getCTX() return ffi.gc(M.BN_CTX_new(),M.BN_CTX_free) end local readUL = (function () ffi.cdef 'int scanf(const char *, ...);' local C,c = ffi.C,ffi.new("uint64_t[1]") return function () C.scanf("%ld",c) return c[0] end end)() do local ctx,D = getCTX(),1000000007ULL local b,d,t = ul2bn(),ul2bn(D),ul2bn() M.BN_mod_exp(b, ul2bn(10ULL), ul2bn(readUL()), d, ctx) M.BN_mod_mul(b, b, ul2bn(4ULL), d, ctx) M.BN_sub_word(b, 1ULL) M.BN_mod_exp(t, ul2bn(3ULL), ul2bn(D-2ULL), d, ctx) M.BN_mod_mul(b, b, t, d, ctx) print(bn2str(b)) end