8
$\begingroup$

Let's say we have a random number consisting of an arbitrary number of digits, such as for example 3097.

This number can be represented as an array of repeated numbers with Mathematica by typing

ConstantArray[3097, n]

For n = 4 the output is

{3097, 3097, 3097, 3097}

What is the code to be used to go from the array and write the "continuous" single number 3097309730973097?

What if we want the number to be repeated 3 times (309730973097), or 10 times, etc?

$\endgroup$
  • $\begingroup$ {3097, 3097, 3097} // Map[ToString] // Apply[StringJoin] // ToExpression, for one. $\endgroup$ – Shredderroy Jul 3 '18 at 16:10
10
$\begingroup$

That can easily be done by separating each number into digits and re-assembling them as Number

{3097, 3097, 3097, 3097} // IntegerDigits // Flatten // FromDigits
$\endgroup$
4
$\begingroup$

Update: A shorter alternative using FromDigits with base 10^commonIntegerLength:

f = FromDigits[#, 10^IntegerLength[#[[1]]]] &;

f @ ConstantArray[3097, 5]

30973097309730973097

Timings: Just in case you need to do this for a large number of long integers, timings for the methods posted so far (fdfid below is the function FromDigits@Flatten@IntegerDigits@#& from halirutan's answer):

SeedRandom[1]
n = RandomInteger[10^16];
m = 100000;
t1 = First[RepeatedTiming[r1 = f@ConstantArray[n, m];]];
t2 = First[RepeatedTiming[r2 = catenateInteger@ConstantArray[n, m];]];
t3 = First[RepeatedTiming[r3 = fdfid @ ConstantArray[n, m];]];
t4 = TimeConstrained[First[RepeatedTiming[r4 = myfun[n, m];]], 5];

Grid[{{"function:", "f", "catenateInteger", "fdfid", "myfun"}, 
 {"timing:", 0.0950, 0.169, 0.637, $Aborted}}, Dividers -> All]

enter image description here

r1 == r2 == r3

True

Original answer:

catenateInteger = Composition[FromDigits, StringJoin, IntegerString]
catenateInteger @ ConstantArray[3097, 5]

30973097309730973097

$\endgroup$
1
$\begingroup$
myfun[mydig_Integer, mynum_Integer] :=  
 Sum[mydig 10^(i Ceiling[Log[10, mydig]] - mynum), {i, mynum}]

so

myfun[3097, 4]

3097309730973097

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.