RosettaCodeData/Task/Modular-exponentiation/Phix/modular-exponentiation.phix
2026-02-01 16:33:20 -08:00

33 lines
1 KiB
Text

with javascript_semantics
include mpfr.e
procedure mpz_mod_exp(mpz base, exponent, modulus, result)
if mpz_cmp_si(exponent,1)=0 then
mpz_set(result,base)
else
mpz exp_copy = mpz_init_set(exponent)
bool bOdd = mpz_odd(exp_copy)
if bOdd then
mpz_sub_ui(exp_copy,exp_copy,1)
end if
mpz_fdiv_q_2exp(exp_copy,exp_copy,1)
mpz_mod_exp(base,exp_copy,modulus,result)
exp_copy = mpz_free(exp_copy)
mpz_mul(result,result,result)
if bOdd then
mpz_mul(result,result,base)
end if
end if
mpz_mod(result,result,modulus)
end procedure
mpz base = mpz_init("2988348162058574136915891421498819466320163312926952423791023078876139"),
exponent = mpz_init("2351399303373464486466122544523690094744975233415544072992656881240319"),
modulus = mpz_init("1e40"),
result = mpz_init()
mpz_mod_exp(base,exponent,modulus,result)
?mpz_get_str(result)
-- check against the builtin:
mpz_powm(result,base,exponent,modulus)
?mpz_get_str(result)