algorithm - 求幂 - 基于三的位置系统
问题描述
我在十进制系统中有一个自然数 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
推荐阅读
- google-bigquery - 数组中的 BigQuery 数组到正确的列
- node.js - TCP Socket服务器节点js冻结
- javascript - TypeError:对不可迭代实例 React/Jest 的解构尝试无效
- python - 根据标识符列表对元素列表进行分组
- python - 在输入文件中读取扁平字典的pythonic方式
- node.js - 如何访问一个文件,它是 Nodejs 上的 2 个目录?
- python-3.x - 如何通过观察连接两个pytorch模型?
- c++ - 编译时二进制搜索树错误的反向迭代器显示“没有匹配的函数调用运算符 =()”
- java - java中如何逐行上传文件到谷歌云存储(PipedInputStream的实现)
- python - 仅合并 Python Pandas 索引或将 multiIndex Cartesian 与 multiIndex 聚合组合以显示正在使用与未使用