C Fast base convert from decimal to ternary -


is there method of changing decimal number ternary ? mean don't want use modulo , divide method, have big decimal number, 128123832812381835828638486384863486.............1237127317237 , on.

also don't want use bigints.

is there method ?

you don't have use divide/modulo. instead, iterate on input digits, low high. each digit position, first calculate 1000....000 in output representation (it's 10x previous power of 10). multiply result digit, , accumulate output representation.

you need routines perform multiplication , addition in output representation. multiplication routine can written in terms of addition routine.

example:

convert 246 (base-10) base-3.

start initialising output "accumulator" a = "0".

initialise "multiplier" m = "1".

note 10 "101" in output representation.

first digit 6, d = "20".

  • multiply: t = d * m = "20" * "1" = "20".
  • accumulate: a = + t = "0" + "20" = "20".
  • update multiplier: m = m * "101" = "1" * "101" = "101".

second digit 4, d = "11".

  • multiply: t = d * m = "11" * "101" = "1111".
  • accumulate: a = + t = "20" + "1111" = "1201".
  • update multiplier: m = m * "101" = "101" * "101" = "10201".

third digit 2, d = "2".

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

so answer "100010".


Comments