Concatenate two integers in Mathematica 7

2019-04-22 01:33发布

问题:

What is the most efficient way to concatenate two positive integers in Mathematica 7?

cc[123, 4567] >> 1234567

What about more than two?

cc[123, 4, 567, 89] >> 123456789

回答1:

This will be slightly faster for many integers, than your last solution:

ToExpression[StringJoin @@ Map[IntegerString, {##}]] &

A more concise alternative is to accept a single argument, assuming it to be a list, rather than a sequence, of numbers to concatenate:

ToExpression@StringJoin@IntegerString@#&

which is based on IntegerString being Listable.



回答2:

This only works properly for short integers because the output must be machine size, but it is the fastest I found:

Compile[{{a, _Integer}, {b, _Integer}}, 
  b + a 10^Floor[1 + Log[10, b]]
]

For longer integers, the fastest I could find is:

FromDigits[{##}, 10^IntegerLength@#2] &

For concatenating many integers, the following was faster than Fold on the one above:

FromDigits[Join @@ IntegerDigits[{##}]] &