RosettaCodeData/Task/Fermat-numbers/Phix/fermat-numbers.phix
2026-02-01 16:33:20 -08:00

52 lines
1.4 KiB
Text

-- demo\rosetta\Fermat.exw
with javascript_semantics
include mpfr.e
procedure fermat(mpz res, integer n)
integer pn = power(2,n)
mpz_ui_pow_ui(res,2,pn)
mpz_add_si(res,res,1)
end procedure
mpz fn = mpz_init()
constant lim = iff(platform()=JS?18:29), -- (see note)
print_lim = iff(platform()=JS?16:20)
atom t
for i=0 to lim do
t = time()
fermat(fn,i)
string ts = elapsed(t,0.2," [%s]")
if i<=print_lim then
printf(1,"F%d = %s%s\n",{i,shorten(mpz_get_str(fn)),ts})
else -- (since printing it takes too long...)
printf(1,"F%d has %,d digits%s\n",{i,mpz_sizeinbase(fn,10),ts})
end if
end for
printf(1,"\n")
constant flimit = iff(platform()=JS?11:13)
for i=0 to flimit do
t = time()
fermat(fn,i)
sequence f = mpz_prime_factors(fn, 200000)
t = time()-t
string fs = "",
ts = elapsed(t,0.2," [%s]")
if length(f[$])=1 then -- (as per docs)
mpz_set_str(fn,f[$][1])
if not mpz_prime(fn) then
if length(f)=1 then
fs = " (not prime)"
else
fs = " (last factor is not prime)"
end if
end if
f = deep_copy(f)
f[$][1] = shorten(f[$][1],ml:=15)
elsif length(f)=1
and mpz_prime(fn) then
fs = " (prime)"
end if
fs = mpz_factorstring(f)&fs
printf(1,"Factors of F%d: %s%s\n",{i,fs,ts})
end for