gpt4 book ai didi

algorithm - 求幂 - 基于三的位置系统

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:16 24 4
gpt4 key购买 nike

我有一个十进制的自然数 x 和一个三进制的自然数 n。如何使用最小乘法次数计算 x^n 的值?

我知道二进制系统的算法,我一直在寻找类比,但没有找到。

最佳答案

也许你需要这样的东西:

function expbycubing(x, n): 

//treat n = 0..2 cases here

switch n % 3:
0: return expbycubing(x * x * x, n shrt 1)
///// note shift in ternary system (tri)201 => (tri)020
1: return x * expbycubing(x * x * x, n shrt 1)
2: return x * x * expbycubing(x * x * x, n shrt 1)

工作的德尔福代码

 function expbycubing(x, n: Integer): int64;
begin
Memo1.Lines.Add(Format('x: %d n: %d', [x, n]));
if n = 0 then Exit(1);
if n = 1 then Exit(x);
if n = 2 then Exit(x * x);
case n mod 3 of
0: Result := expbycubing(x * x * x, n div 3);
1: Result := x * expbycubing(x * x * x, n div 3);
2: Result := x * x * expbycubing(x * x * x, n div 3);
end;
end;

var
i: Integer;
begin
for i := 12 to 12 do
Memo1.Lines.Add(Format('%d: %d', [i, expbycubing(2, i)]));
end;

日志:

x: 2  n: 12
x: 8 n: 4
x: 512 n: 1
12: 4096

关于algorithm - 求幂 - 基于三的位置系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com