C快速基数从十进制转换为三进制 [英] C Fast base convert from decimal to ternary

查看:263
本文介绍了C快速基数从十进制转换为三进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将十进制数更改为三进制?
我的意思是我不想使用取模和除法,我有非常大的十进制数,类似128123832812381381835828828486486863486 ............. 1237127317237等。

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.

也不想使用bigints。

Also don't want to use bigints.

有什么方法吗?

推荐答案

您不必使用除法/取模。而是从低到高依次遍历输入数字。对于每个数字位置,首先计算输出表示中 1000 .... 000 的值(是前一个乘方10的10倍)。然后将该结果乘以数字,然后累加到输出表示形式中。

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.

示例:

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

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

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

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

初始化乘数 m = 1

还要注意,输出表示中的10是 101

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

第一个数字为6 ,即 d = 20


  • 相乘: t = d * m = 20 * 1 = 20

  • 累加: a = a + t = 0 + 20 = 20

  • 更新乘数: m = m * 101 = 1 * 101 = 101

  • Multiply: t = d * m = "20" * "1" = "20".
  • Accumulate: a = a + t = "0" + "20" = "20".
  • Update multiplier: 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

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

第三位是2 ,即 d = 2


  • 相乘: t = d * m = 2 * 10201 = 21102

  • 累加: a = a + t = 1201 + 21102 = 100010

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

所以答案是 100010

这篇关于C快速基数从十进制转换为三进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆