From 37e23e6dba8960e1bd04a40de5c761635ef2594f Mon Sep 17 00:00:00 2001 From: YangFong Date: Sun, 20 Mar 2022 14:47:39 +0800 Subject: [PATCH] docs: add a description of the solution to lcci problem: No.08.05 No.08.05.Recursive Mulitply --- lcci/08.05.Recursive Mulitply/README.md | 53 +++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/lcci/08.05.Recursive Mulitply/README.md b/lcci/08.05.Recursive Mulitply/README.md index e24a862571296..39f1f603cecea 100644 --- a/lcci/08.05.Recursive Mulitply/README.md +++ b/lcci/08.05.Recursive Mulitply/README.md @@ -31,6 +31,59 @@ +~~**最佳方案:**~~ + +~~直接返回 `A * B`~~ + +正常递归,叠加总和 + +```txt +MULTIPLY(A, B) + if A == 0 || B == 0 + return 0 + A + multiply(A, B - 1) +``` + +优化 1: + +由数值较小的数字决定递归层次 + +```txt +MULTIPLY(A, B) + if A == 0 || B == 0 + return 0 + return max(A, B) + multiply(max(A, B), min(A, B) - 1) +``` + +优化 2: + +使用位移减少递归层次 + +```txt +MULTIPLY(A, B) + return (B % 1 == 1 ? A : 0) + (B > 1 ? MULTIPLY(A + A, B >> 1) : 0) +``` + +可进一步,转换为循环,虽然并不符合递归主题。 + +> A 与 B 皆为**正整数**,初始值不会为 0,所以终止条件是 `B != 1` + +```txt +MULTIPLY(A, B) + T = min(A, B) + A = max(A, B) + B = T + r = 0 + while B != 1 { + if B % 2 == 1 { + r = r + A + } + A = A + A + B = B >> 1 + } + return res + A +``` + ### **Python3**