C 从十进制到三进制的快速基数转换

发布于 2024-11-04 06:43:15 字数 173 浏览 1 评论 0原文

有没有什么方法可以将十进制数更改为三进制数? 我的意思是我不想使用模和除法,我有很大的十进制数,例如 128123832812381835828638486384863486........................1237127317237 等等。

也不想使用bigint。

有什么方法吗?

is there any method of changing decimal number to ternary ?
I mean i don't want to use modulo and divide method, i have very big decimal number, something like 128123832812381835828638486384863486.............1237127317237 and so on.

Also don't want to use bigints.

Is there any method ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2024-11-11 06:43:15

您不必使用除法/模数。相反,从低到高迭代输入数字。对于每个数字位置,首先计算输出表示中的 1000....000 (它是之前的 10 次幂的 10 倍)。然后将该结果乘以数字,并累加到输出表示形式中。

您将需要在输出表示中执行乘法和加法的例程。乘法例程可以用加法例程来编写。

示例:

将 246(基数 10)转换为基数 3。

首先初始化输出“累加器”a = “0”

初始化“乘数”m = “1”

另请注意,10 在输出表示中是 "101"

第一个数字是 6,即 d = "20"

  • 乘法:t = d * m = "20" * "1" = "20"
  • 累加:a = a + t = "0" + "20" = "20"
  • 更新乘数:m = m * "101" = "1" * "101" = "101"

第二个数字是 4,即 d = "11"

  • 乘法:t = d * m = "11" * "101" = "1111"
  • 累加:a = a + t = "20" + "1111" = "1201"
  • 更新乘数:m = m * "101" = "101" * "101" = "10201"

第三位数字是 2,即 d = "2"

  • 乘法:t = d * m = "2" * "10201" = "21102"
  • 累加:a = a + t = "1201" + "21102" = "100010"

所以答案是“100010”

You don't have to use divide/modulo. Instead, iterate over the input digits, from low to high. For each digit position, first calculate what 1000....000 would be in the output representation (it's 10x the previous power of 10). Then multiply that result by the digit, and accumulate into the output representation.

You will need routines that perform multiplication and addition in the output representation. The multiplication routine can be written in terms of the addition routine.

Example:

Convert 246 (base-10) to base-3.

Start by initialising output "accumulator" a = "0".

Initialise "multiplier" m = "1".

Note also that 10 is "101" in the output representation.

First digit is 6, which is d = "20".

  • Multiply: t = d * m = "20" * "1" = "20".
  • Accumulate: a = a + t = "0" + "20" = "20".
  • Update multiplier: m = m * "101" = "1" * "101" = "101".

Second digit is 4, which is d = "11".

  • Multiply: t = d * m = "11" * "101" = "1111".
  • Accumulate: a = a + t = "20" + "1111" = "1201".
  • Update multiplier: m = m * "101" = "101" * "101" = "10201".

Third digit is 2, which is d = "2".

  • Multiply: t = d * m = "2" * "10201" = "21102".
  • Accumulate: a = a + t = "1201" + "21102" = "100010".

So the answer is "100010".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文