title: A square of text

text:
# Question
Title: A square of text
## The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

### Example

```
Input:
Hi, world

Output:
Hi,
 wo
rld

```

## Test Cases

```
Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
 ipsu
m dol
or si
t amt

Input:
H

Output:
H

```

## Rules

* This is , so shortest answer in bytes wins! Tiebreaker is most upvoted answer.
* Standard loopholes are forbidden.

# Answer
> 10 votes
# 05AB1E, 5 bytes

```
Dgtô«

```

Try it online!

```
D    duplicate a (implicit input)
g    length of a
t    square root of a
ô    push a split in pieces of b
«    join by newlines (implicit output)

```

# Answer
> 22 votes
# Vim, ~~59, 57~~, 48 bytes/keystrokes

```
$:let @q=float2nr(sqrt(col('.')))."|li<C-v><cr><C-v><esc>@q"<cr>@q

```

Since V is backwards compatible, you can Try it online!

I randomly received an upvote on this answer, so I looked over it again. My vim-golfing skills have greatly increased over the last 7 months, so I saw that this answer was very poorly golfed. This one is much better.

# Answer
> 15 votes
# Brainfuck, ~~116~~ 112 bytes

```
>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

```

Try it online!

Safe in flavours of BF that does not mask the cells with `256`, does not support null bytes.

Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.

## Explanation

The program is divided into 3 stages:

```
Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

```

### Stage 1

In this stage, we put all the characters onto the tape, while keeping count of the number of characters.

This is the tape for the input `abcdefghi` after this tape:

```
000 009 000 000 095 096 097 098 099 100 101 102 103
             ^

```

The `009` is the count.

For each character, we move the the first zero on the left `[<]` and then add one to the count `<<+>>>`, and then move to the rightmost zero `[>]` to get ready for the next character.

## Stage 2

This stage does the square root of the length stored in the second cell.

It keeps subtracting by `1, 3, 5, 7, ...` until the number reaches zero, while keeping check of the number of iterations.

It works because square numbers can be expressed as `1 + 3 + 5 + ...`.

## Stage 3

Denote the square root of the length found above as `n`.

This stage outputs `n` characters at a time, and then output a newline, until the tape is cleared.

# Answer
> 11 votes
## Python 2, 55 bytes

```
s=input()
n=int(len(s)**.5)
while s:print s[:n];s=s[n:]

```

# Answer
> 8 votes
# MATL, 6 bytes

```
tnX^e!

```

**Try it online!**

### Explanation

```
t     % Take input implicitly. Push another copy
n     % Get number of elements of the copy
X^    % Take square root
e     % Reshape the input into that number of rows, in column-major order
      % (which means: down, then across)
!     % Transpose so that text reads horizontally. Implicitly display

```

# Answer
> 7 votes
# Jelly, ~~8~~ 7 bytes

```
sLÆ½$j⁷

```

Saved a byte thanks to @Dennis.

Try it online.

## Explanation

```
sLÆ½$j⁷  Input: string S
    $    Monadic chain
 L         Get the length of S
  Æ½       Take the integer square root of it, call it n
s        Split S into chunks of size n
     j⁷  Join using newline

```

# Answer
> 7 votes
## JavaScript (ES7), 49 bytes

```
s=>s.match(eval(`/.{${s.length**.5}}/g`)).join`
`

```

44 bytes in Firefox Nightly 43-46 only (`**` was introduced some time between Firefox Nightly 42 and 43 and `g` as a separate parameter was removed some time between Firefox Nightly 46 and 47):

```
s=>s.match(`.{${s.length**.5}}`,`g`).join`
`

```

# Answer
> 7 votes
# J, 9 bytes

```
$~,~@%:@#

```

This is a monadic hook over the input string:

```
$~ ,~@%:@#

```

The right tine is a series of compositions:

```
,~ @ %: @ #

```

The left is a shaping verb, switched such that it works in the hook format.

Here are some intermediate results:

```
   # 'hiya'
4
   %:@# 'hiya'
2
   ,~@%:@# 'hiya'
2 2

```

In words:

```
   size =: #
   sqrt =: %:
   dup =: ,~
   on =: @
   shape =: $~
   block =: shape dup on sqrt on size
   block 'Hello, World! :)'
Hell
o, W
orld
! :)

```

# Answer
> 5 votes
## Perl, 23 + 4 (`-pF` flags) = 27 bytes

*-2 bytes thanks to @DomHastings*
*-1 bytes thanks to @DomHastings*

```
$==sqrt@F;s/.{$=}/$&
/g

```

Try it online!

**Expanations** : computes the square root (lets call it `S` for the explanation) of the size of the input (it will be always be an integer) (`@F` is used in scalar context, thus returning its size), then add a newline after each bloc of `S` characters.

# Answer
> 5 votes
# C, 64 bytes

Call `f()` with the string to square.

```
m;f(char*s){for(m=sqrt(strlen(s));*s;s+=m)printf("%.*s\n",m,s);}

```

Try it on ideone.

# Answer
> 4 votes
# Python, ~~94~~ ~~75~~ ~~71~~ ~~65~~ 63 bytes

```
import re;lambda r:"\n".join(re.findall("."*int(len(r)**.5),r))

```

Old version:

```
lambda r:"\n".join(map("".join,zip(*[iter(r)]*int(len(r)**.5))))

```

# Answer
> 4 votes
# 05AB1E, ~~8~~ 6 bytes

*Thanks to @quartata for letting me know about the square-root function*

```
Dgtô¶ý

```

**Try it online!**

### Explanation

```
D     Implicit input. Duplicate
g     Number of elements
t     Square root
ô     Split into chunks of that length
¶     Push newline character
ý     Join list by newlines. Implicit display

```

# Answer
> 4 votes
# Cheddar, 27 bytes

```
s->s.chunk(s.len**.5).vfuse

```

I added the `.chunk` function a while ago but I removed it in the transition to the new stdlib format and forgot to re-add it. Cheddar has a dedicated `sqrt` operator but `**.5` is shorter

Try it online!

## Explanation

```
s ->              // Function with argument s
    s.chunk(      // Chunk it into pieces of size...
      s.len ** .5 // Square root of length.
    ).vfuse       // Vertical-fuse. Join on newlines

```

# Answer
> 4 votes
## zsh, ~~36~~ 33 bytes

```
fold -`tr -d .<<<$[$#1**.5]`<<<$1

```

Try it online!

Takes input as a command line argument, outputs to STDOUT.

```
                   $#1             # get the length of the input string
                 $[   **.5]        # take it to the .5 power (sqrt)
              <<<                  # and pass the result to
       tr -d .                     # tr, to delete the trailing decimal point
                                   #    (sqrt(9) is 3. instead of 3)
     -`                    `       # give the result as a command line flag to
fold                               # the fold util, which wraps at nth column
                            <<<$1  # pass the input as input to fold

```

# Answer
> 4 votes
# Dyalog APL, 10 bytes

```
⊢⍴⍨2⍴.5*⍨≢

```

Explanation:

```
         ≢   length of the argument
     .5*⍨    square root
   2⍴        reshape that to a length-2 vector
⊢⍴⍨          reshape the input by that vector

```

Tests:

```
      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world'
Hi,
 wo
rld
      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world! Hello'
Hi,
worl
d! H
ello
      (⊢⍴⍨2⍴.5*⍨≢)'Lorem ipsum dolor sit amt'
Lorem
 ipsu
m dol
or si
t amt
      (⊢⍴⍨2⍴.5*⍨≢) 'H'
H

```

# Answer
> 3 votes
# CJam, 8 bytes

```
l_,mQ/N*

```

**Try it online!**

### Explanation

```
l     e# Read line from input
_,    e# Duplicate. Get length
mQ    e# Integer square root
/     e# Split into pieces of that size
N*    e# Join by newline. Implicitly display

```

# Answer
> 3 votes
# Pyth, 8 bytes

```
jcs@lQ2Q

```

Try it online

### How it works

```
    lQ     length of input
   @  2    square root
  s        floor
 c     Q   chop input into that many equal pieces
j          join on newline

```

# Answer
> 3 votes
# Bash + GNU utilities, 25

```
fold -`dc -e${#1}vp`<<<$1

```

Not so different to @Doorknob's answer, but `dc` is a shorter way to get the square root.

# Answer
> 3 votes
# , 11 chars / 14 bytes

```
ѨĊ(ï,√ ïꝈ⸩Ė⬮

```

`Try it here (ES6 browsers only).`

Generated using this code (run in the interpreter's browser console):

```
c.value=`Ѩ${alias(_,'chunk')}(ï,√ ïꝈ⸩${alias(Array.prototype,'mjoin')}⬮`

```

# Answer
> 3 votes
## Brainfuck, 83 bytes

```
,[>+[>+<-],]
>
[
  >>[<+<-->>-]
  +<[>+<-]
  <-
]
<<
[
  [<]
  >.,
  >[>]
  >>+>-[<]
  <[[>+<-]++++++++++.,<<]
  <
]

```

Try it online!

This uses the same idea as Leaky Nun's answer. He asked for help golfing it in chat, then suggested that I add this as a new answer. (Actually what I wrote in chat was an 84-byte solution very similar to this.)

For the sake of comparison, an extra `>` is needed at the beginning for brainfuck implementations that don't allow negative memory addresses.

As expected, this finds the length of the input, then takes the square root, then prints the lines accordingly. It takes advantage of perfect squares being partial sums of `1 + 3 + 5 ...`.

# Answer
> 3 votes
# Brain-Flak, ~~110~~ 96 bytes

```
([]<>){({}{}(({}[()])))}{}{({}()<(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>)>)}{}{}{({}<>)<>}<>

```

Try it online!

# Second solution, 96 bytes

```
(([]<>)<{({}({})({}[()]))}{}>){({}(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>))}{}{}{({}<>)<>}<>

```

Try it online!

## Explanation

Here I explain the first solution, both are the same length but I like the first one because it is cooler and employs some nice tricks.

The most important part of the code is a modified square root function I wrote some time ago. The original version was

```
{({}[({})({}())])}{}

```

And this works, but we actually want two copies of the negative square root. Why? We need two copies because we are looping through the string at two levels, one to make the lines and one to count the number of lines. We want it to be negative because looping with negatives is cheaper.

To make this negative we move around the `[...]` so it looks like this

```
{({}({})({}[()]))}{}

```

To make two copies we change when pops occur

```
{({}{}(({}[()])))}{}

```

Now that we have that bit we can put it together with a stack height to get the first chunk of code we need.

```
([]<>){({}{}(({}[()])))}{}

```

We move to the offstack because our square root function needs two free zeros for computation, and because it makes stuff a little bit cheaper int he future in terms of stack switching.

Now we construct the main loop

```
{({}()<(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>)>)}{}{}

```

This is pretty straight forward, we loop n times each time moving n items and capping it with a new line (ASCII 10).

Once the loop is done we need to reverse the order of our output so we just tack on a standard reverse construct.

```
{({}<>)<>}<>

```

# Answer
> 2 votes
## PHP, 51 bytes

```
<?=join("
",str_split($x=$argv[1],strlen($x)**.5));

```

# Answer
> 2 votes
# Perl 6, 38 bytes

```
$_=get;.put for .comb: .chars.sqrt.Int

```

### Explanation:

```
$_ = get;          # get a single line of input

$_.put             # print with trailing newline

for                # every one of the following:

$_.comb:           # the input split into

$_.chars.sqrt.Int  # chunks of the appropriate size

```

# Answer
> 2 votes
# Ruby `-p`, ~~40~~ ~~33~~ 30 bytes

-7 bytes from @Jordan.

```
gsub(/#{?.*~/$/**0.5}/){$&+$/}

```

Try it online!

# Answer
> 2 votes
# Cheddar, 57 bytes

```
n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5)

```

Since variables are broken, I would have to pass in variables through lambda application.

Also, it turns out that even if variables worked, it would still be shorter to use lambda application.

### Usage

```
cheddar> (n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5))("abcd")
"ab
cd"

```

# Answer
> 2 votes
## Pyke, 5 bytes

```
l,fnJ

```

Try it here!

# Answer
> 2 votes
# PowerShell, 56 ~~58~~ ~~61~~ bytes

```
param($i)$i-replace".{$([Math]::Sqrt($i.Length))}",'$&
'

```

# Answer
> 2 votes
# Java 1.7, 110 bytes

```
void f(String s){for(int i=-1,k=(int)Math.sqrt(s.length());++i<k;)System.out.println(s.substring(i*k,i*k+k));}

```

Try it! (Ideone)

I tried another approach with a function returning the result as a string, but just having to declare the string and the return statement is already more expensive (byte-count-wise) than the print statement.

Gotta love Java's verbosity... :)

# Answer
> 2 votes
# , ~~59~~ 54 bytes

```
function(s)write(el(strsplit(s,'')),1,nchar(s)^.5,,'')

```

Try it online!

Prints with a trailing newline. Surprisingly short, considering how badly R handles strings.

# Answer
> 2 votes
# K (ngn/k), 11 bytes

```
{(2#%#x)#x}

```

Try it online!

---

the bracketed expression returns list `5 5` for input "Lorem ipsum dolor sit amt". it reads "2 take sqrt count x", where x is the string argument. then `(5 5)#x` means "cut x into 5 lists each of length 5". with this we get:

```
  {(2#%#x)#x}"Lorem ipsum dolor sit amt"
("Lorem";" ipsu";"m dol";"or si";"t amt")

```

# Answer
> 2 votes
# Vyxal `jr`, 3 bytes

```
L√/

```

Try it Online!

```
  / # (Implicit input) divided into...
 √  # Square root of...
L   # Length of...
    # (implicit input)
  / # Pieces.

```

# Answer
> 2 votes
# Risky, 14 bytes

```
2_2+_2+__1+_1*__?*_1/}!?*_1

```

Try it online!

### Explanation

So many no-ops... 0\__0

Parse tree:

```
             *
      +             /
2      _      _      }
   +      +      *      *
 _  _   _  _   _  _   !  _
  2  2   1  1   ?  1   ?  1

```

How it works:

```
                ?            The input string (as a list of charcodes)
              __ *_1         (no-ops)
                    /        Group into sublists of length...
                     }       square root of...
                      !      length of...
                       ?     the input string again
                        *_1  (no-ops)
2_2+_2+__1+_1                Generate the number 10 in a needlessly complicated way
             *               Join the list of lists on 10 (newline)
                             Output the resulting list of numbers as a string

```

# Answer
> 1 votes
# Convex, 7 bytes

```
_,mQ/N*

```

Try it online!

Fun fact:

`_,mQ/\*` also works on TIO due to how it works.

How have I forgotten to make a 1-char square root op?

# Answer
> 1 votes
## Matlab, 28 bytes

```
@(s)reshape(s,nnz(s)^.5,[])'

```

`reshape` puts output in columns first, so we have to transpose the whole thing to get the desired output.

# Answer
> 1 votes
# PHP, 47 bytes

```
<?=chunk_split($a=$argv[1],strlen($a)**.5,"
");

```

For multibyte strings, 66 bytes

```
<?=preg_replace("/.{1,".sqrt(strlen($a=$argv[1]))."}/u","$0
",$a);

```

# Answer
> 1 votes
# Silicon, 6 bytes

I added some commands right after I noticed this challenge.

```
iLqnåê

```

**Explanation:**

```
iLqnåê

i          Input
  q        Square root of...
 L         Length
   n       Convert to integer
    å      Split into chunks of n
     ê     Join at newlines

```

# Answer
> 1 votes
# QBasic, 60 bytes

Nothing special here... just your BASIC program.

```
INPUT i$
t=SQR(len(i$))
FOR x=0TO t-1
?MID$(i$,x*t+1,t)
NEXT

```

# Answer
> 1 votes
# q/kdb+, ~~25~~ 22 bytes

**Solution:**

```
-1{(2#6h$sqrt(#)x)#x};

```

**Example:**

```
q)-1{(2#6h$sqrt(#)x)#x}"Lorem ipsum dolor sit amt";
Lorem
 ipsu
m dol
or si
t amt

```

**Explanation:**

```
-1{(2#6h$sqrt count x)#x}; / ungolfed solution
  {                     }  / lambda function
                      #x   / take from x (input)
   (                 )     / do everything in the brackets first
              count x      / length of x
         sqrt              / calculate square-root
      6h$                  / cast to integer
    2#                     / duplicate this number, e.g. 5->(5;5)
-1                       ; / print to stdout

```

# Answer
> 1 votes
# SOGL V0.12, 1 byte

Try it Here! \- this expects the input on the stack as a function, so there it's called as a function `F` and then, in the next line, `,` pushes the input and `F` executes the function.

### without builtins, 3 bytes

```
l√n

```

Try it Here!
push length, square root it, split input into strings of that length, implicitly output joined with newlines

# Answer
> 1 votes
# Perl 6, ~~28~~ 27 bytes

*-1 byte thanks to nwellnhof*

```
{.comb(.comb**.5+|0)>>.say}

```

Try it online!

# Answer
> 1 votes
# Momema, 99 bytes

```
03i00+1*0*0*-9i=+1**00+-4*0q00+*0-+1+*1*1 1+1*1q=*02*1o03*1p0-9*+4*00+1*03+-1*3p=*3 2+-1*2-9 10o=*2

```

Try it online!

# Explanation

```
                 # -- Read the input onto the tape.
                 # -- Set aside the first 4 cells as variables.
0   3            # p = 3
i   0            # do {
0   +1*0         #   p = p+1
*0  *-9          #   tape[p] = getchar()
i   =+1**0       # } while (tape[p] != -1)
0   +-4*0        # p = p - 4
                 # -- Calculate the square root of the input length.
q   0            # do {
0   +*0-+1+*1*1  #   p = p - (1 + r + r)
1   +1*1         #   r = r + 1
q   =*0          # } while (p)
                 # -- Print the formatted output.
2   *1           # i = r
o   0            # do {
3   *1           #   j = r
p   0            #   do {
-9  *+4*0        #     putchar(tape[p + 4])
0   +1*0         #     p = p + 1
3   +-1*3        #     j = j - 1
p   =*3          #   } while (j)
2   +-1*2        #   i = i - 1
-9  10           #   putchar(10)
o   =*2          # } while (i)

```

# Answer
> 1 votes
## Python 3.8, 68 bytes

```
a=int(len(s:=input())**.5)
for i in range(0,a**2,a):print(s[i:][:a])

```

Not the shortest Python answer, but also not the longest. Goes through the string by intervals of the square root of the length of the string. I saved a byte by using Python 3.8's new-fangled assignment expressions.

# Answer
> 1 votes
# Kotlin, 57 bytes

```
fun String.s()=chunked(sqrt(length+.0).toInt(),::println)

```

Explanation:

```
fun String.s()=   # Extension method on the string, so we can avoid declaring a param
chunked           # Actually this method does all the heavy lifting, it splits the string into a list of size N strings
(sqrt(length+.0)  # Kotlin's sqrt only takes double and produces double :/
.toInt(),         # So we need to cast the result for chunked in an ugly way :/
::println)        # But hey, applying a transform to print is actually included for free!

```

# Answer
> 1 votes
# Python 3, 78 bytes

```
def f(s):
	r=int(len(s)**.5)
	return'\n'.join([s[i*r:i*r+r]for i in range(r)])

```

Try it online!

# Answer
> 1 votes
# Stax, 3 bytes

```
:Jm

```

Run and debug it at staxlang.xyz!

Very simple. `:J` squarifies an array. That `m` is necessary because Stax will print a list of strings on one line.

### Without the builtin, six bytes

```
c%|q/m

```

Run and debug it at staxlang.xyz!

Copy the string (`c`) and take its length (`%`). Square root that length (`|q`), and split the string into substrings of that (square-rooted) length (`/`).

# Answer
> 1 votes
## TI-Basic, 33 Bytes

```
Input Str1
length(Str1→Z
For(X,1,Z,√(Z
Disp sub(Str1,X,√(Z
End

```

This is not a particularly interesting answer, due to the limitations of TI-Basic, but I like the language too much to resist. Note that TI-Basic is tokenized, so byte count for the program is not the same as character count.

# Answer
> 1 votes
# Zsh, ~~54~~ 51 bytes

***-3** by `^=` instead of `=0^()`.*

```
((n=$#1,l^=n**0.5))
eval '<<<${1:'{0..$n..$l}':$l}'

```

~~Try it online!~~ Try it online!

Shoutouts to `eval` jank.

```
((n=$#1,l^=n**0.5))              # the xor with 0 casts n**0.5 to an integer
eval '<<<${1:'           ':$l}'  # when eval'd, prints a subtring of length l
              {0..$n..$l}        # brace expansion: {0..4..16} => 0 4 8 12 16

```

I left in `set -x` in the TIO link, scroll down to the debug section to see exactly what happens with the brace expansion.

# Answer
> 1 votes
# Vyxal `j`, 1 byte

```
²

```

Try it Online!

Yes, there's a built in for it.

"But there's already another vyxal answer!" This is using 2.16.0 while the other one is using \<2.4.0

# Answer
> 0 votes
## ListSharp, 157 bytes

```
STRG a=READ[<here>+"\\a.txt"]
NUMB b=(int)Math.Sqrt(a LENGTH)
[FOREACH NUMB IN 0 TO b-1 AS x]
{
STRG t=GETRANGE a FROM [x*b+1] TO [x*b+b]
ROWS f=f+t
}
SHOW=f

```

reads text from local file `a.txt` , im using embedded c# code and other tricks to make this work. feel free to ask me questions about this code or listsharp in general

# Answer
> 0 votes
# C, 64 bytes

```
f(s,m,k){for(m=k=sqrt(strlen(s));k--;s+=m)printf("%.*s\n",m,s);}

```

Inspired by the other C answer. Only works on platforms where `int` has the same size as `char*` (e.g. 32-bit Windows).

# Answer
> 0 votes
# Lua, 68 Bytes

```
o=io.read()for s in o:gmatch(("."):rep(math.sqrt(#o)))do print(s)end

```

Simple and dirty, just how I like it. I use o=io.read() instead of function(o) Which works out as the same length, to save from having to add an extra "end" at the end.

Pretty simple in functionality, it just uses gmatch to loop through the string in chunks of math.sqrt(#o), Which is the square root of the length of the string. Sadly, Lua patterns don't offer the regex functionality of {} to denote a specific count, so I had to do :rep() instead.

# Answer
> 0 votes
# Racket 102 bytes

```
(λ(s)(let*((l(string-length s))(q(sqrt l)))(for((i(range 0 l q)))(displayln(substring s i(+ i q))))))

```

More readable form:

```
(define (f s)
  (let* ((l (string-length s))
         (q (sqrt l)))
    (for((i(range 0 l q)))
      (displayln (substring s i(+ i q))))))

```

Testing:

```
(f "Lorem ipsum dolor sit amt")
Lorem
 ipsu
m dol
or si
t amt

```

# Answer
> 0 votes
# ISOLADOS, 93 bytes

```
ISOLAAAADOS ISOLAAAAAADOS ISOLAAAAAAAADOOS ISOLAAADOOOOOOS ISOLAAAAAAAADOOOS ISOLAAAAAAAAADOS

```

---

```
ISOLAAAADOS          input
ISOLAAAAAADOS        duplicate
ISOLAAAAAAAADOOS     length
ISOLAAADOOOOOOS      square root
ISOLAAAAAAAADOOOS    a split into chunks of length b
ISOLAAAAAAAAADOS     join by new lines

```

# Answer
> 0 votes
## QBIC, 41 bytes

```
;c=sqr(len(A))[1,c|?mid$$|(A,q,c) q=c*a+1

```

Unfortunately, it doesn't work on text parameters with spaces in it. I'll put it on the QBIC todo-list.

Explanation:

```
;           gets the input as string A$
sqr(len(A)) calls the QBasic square root function, with the length of A$ as argument
[1,c...     Loops from 1 to the height of the square
?mid$$|(..) Prints the middel part of A$. The '$' has a reserved meaning in QBIC and needs to be escaped
q=c*a+1     Sets the starting point of the next mid$
<implicit>  NEXT

```

Note that a more modern version of QBIC can solve this in 27 bytes:

```
_L;|g=sqr(a)[1,a,g|?_sA,b,g

```

Improvements are: inline cmd-arg-grabbing (`;`), implementation of `len` (`_L` or `_l`) and substring (`_s`). Also, I've improved conditions and workings of the FOR-loop itself.

# Answer
> 0 votes
# Japt `-R`, ~~7~~ ~~6~~ 4 bytes

```
òUÊ¬

```

Try it

```
òUÊ¬     :Implicit input of string U
ò        :Partition into chunks of length
 UÊ      :  Length of U
   ¬     :  Square root
         :Implicitly join with newlines and output

```

# Answer
> 0 votes
# K (oK), 14 bytes

**Solution:**

```
`0:#[2#%#x]x:;

```

Try it online!

**Example:**

```
`0:#[2#%#x]x:"Lorem ipsum dolor sit amt";
Lorem
ipsu
m dol
or si
t amt

```

**Explanation:**

Similar to my q/kdb+ solution, but a little shorter. Use `#` to reshape string into a square:

```
`0:#[2#%#x]x:; / the solution
`0:          ; / print to stdout and swallow return value
           x:  / save input as x
   #[     ]    / reshape
        #x     / count x
       %       / sqrt
     2#        / duplicate

```

# Answer
> 0 votes
# Ly, 31 bytes

```
irysp>l12/^s<[ol,s!['
o>s<1$]p]

```

Try it online!

Try a square version online, for fun

# Answer
> 0 votes
# JavaScript (Node.js), 54 bytes

```
s=>[...s].map((c,i)=>++i%s.length**.5?c:c+`\n`).join``

```

Try it online!

# Answer
> 0 votes
# Python 3, 76 bytes

I understand the length of my answer, but I didn't want to copy off the other people that did python, so I took the bit longer route (by like an extra 20 some bytes).

```
i=input()
for c in range(len(i)):print(i[c],end="\n"*((c+1)%len(i)**0.5==0))

```

Try it online!

So rather than cut my string after I use the part I want, I keep printing characters until I get to the edge of the square, then I add a newline and keep spewing characters and doing that till we get to the end.

# Answer
> 0 votes
# C#, 151 Bytes

```
static string T(string c){string s="";int a=(int)Math.Sqrt(c.Length);for(int i=0;i<c.Length;i++){s=s+c.Substring(0,a)+"\n";c=c.Remove(0,a);}return s;}

```

# Answer
> 0 votes
# Japt `-R`, 4 bytes

```
òUÊq

```

Try it online!

## Explanation:

```
òUÊq
ò        // Split the input into slices of length:
   q     //   Square root of
 UÊ      //   Length of the input
-R       // Join with newlines

```

# Answer
> 0 votes
# Tcl, ~~100~~ ~~98~~ 65 bytes

```
{s {regsub -all -- (.{[expr int([string le $s]**.5)]}) $s \\1\n}}

```

Try it online!

# Answer
> 0 votes
# Lua, 65 bytes

```
t=io.read()for i in t:gmatch(('.'):rep((#t)^0.5)) do print(i) end

```

Try it online!

Explanation:

```
t=io.read()           -- Read input string
for i in              -- Iterator-based loop
    t:gmatch(         -- over results of pattern-matching on input
        ('.'):rep(    -- Make string of dots
            (#t)^0.5) -- square root from input length string long
        )             -- …which is a pattern for matching that long substring
    )
do                    -- Loop body
    print(i)          -- Print our match and newline
end

```

TL;DR: it uses pattern-matching (Lua version of regexp) to get square root of input long substrings and prints them.

# Lua, 84 bytes (with UTF-8 support)

```
t=io.read()for i in t:gmatch(('.[\128-\191]*'):rep(utf8.len(t)^0.5)) do print(i) end

```

Try it online!

Same idea as above, but with few UTF-8 tricks.

# Answer
> 0 votes
# Runic Enchantments, 19 bytes

```
qA,r\;>i:l͍'
$ka$L

```

Try it online!

Outputs with a trailing newline because its cheaper to loop and wait for stack underflow to cause program termination than to figure out if anything's left on the stack to print. As such the required terminator `;` goes unexecuted.

Inputs that are not capable of being square are output as tall rectangles, as computation required to coerce a square through trailing spaces aren't necessary due to challenge spec regarding inputs.

Additionally, spaces need to be escaped in order for the input to be treated as a single string (rather than multiple space-separated strings).

# Answer
> 0 votes
# Elm 0.19, 112 bytes

```
import List.Extra as L
s l=List.concat<|List.intersperse['\n']<|L.groupsOf(floor<|sqrt<|toFloat<|List.length l)l

```

Input and output as a list of characters. See it working here.

# Answer
> 0 votes
# C#, 180 bytes

```
using System;public class P{public static void Main(string[]a){var d=(int)Math.Sqrt(a[0].Length);string f="";for(int i=0;i<d;i++){f+=a[0].Substring(i*d,d)+"\n";}Console.Write(f);}}

```

Try Online

# Answer
> 0 votes
# MathGolf, 5 bytes

```
h√i/n

```

Try it online!

Unnecessarily long, the `i` shouldn't be needed in my opinion. For operators where float behavior is undefined, the float is normally cast to an integer and used in the operation. This seems to be forgotten for string division, which leads to the extra byte.

## Explanation

```
h       length of array/string without popping
 √      pop a : push(sqrt(a))
  i     convert to integer
   /    split strings
    n   map array with newlines

```

# Answer
> 0 votes
# Python 3, 54 bytes

```
lambda s:fill(s,int(len(s)**.5))
from textwrap import*

```

Try it online!

In Python 3 the `textwrap` module can be used to perform this task.

# Answer
> 0 votes
# Factor \+ `math.unicode`, <sup>~~39~~</sup> 38 bytes

```
[ dup length √ 1 /i group "\n"join ]

```

Try it online!

## Explanation:

* `dup` Duplicate the input.

**Stack:** (e.g.) `"Hi, world" "Hi, world"`
* `length` Get the length.

**Stack:** `"Hi, world" 9`
* Take the square root.

**Stack:** `"Hi, world" 3.0`
* `1 /i` Convert to an integer. This is shorter than `>integer`.

**Stack:** `"Hi, world" 3`
* `group` Split a sequence into groups indicated by the integer on top of the data stack.

**Stack:** `{ "Hi," " wo" "rld" }`
* `"\n"join` Join each string in a sequence into a newline-delimited string.

**Stack:** `"Hi,\n wo\nrld"`

# Answer
> 0 votes
# Canvas, 3 bytes

```
ｌ√ｎ

```

Try it here!

Ties Vyxal and uses pretty much the same approach but without those icky yucky awful terrible flags.

# Answer
> 0 votes
# Brachylog, 7 bytes

```
ẹġṁcᵐẉᵐ

```

Try it online!

### Explanation

```
ẹ        Convert the input string into a list of characters
 ġ       Split that list into groups of equal length
  ṁ      The result must be a square matrix
   cᵐ    Concatenate each row back into a string
     ẉᵐ  Print each row with a trailing newline

```

The solution would be 5 bytes if lists of lines were acceptable output, or 3 bytes if a list of lists of characters were acceptable.

# Answer
> 0 votes
# Thunno 2 `N`, 3 bytes

```
lƭ/

```

Attempt This Online!

#### Explanation

```
lƭ/  # Implicit input
l    # Length of input
 ƭ   # Square root
  /  # Split into that
     # many pieces
     # Implicit output,
     # joined on newlines

```

---
Tags: code-golf, string, grid
---


title: Get the century of a year

text:
# Question
Title: Get the century of a year
Your program has to have an year like `1957` to be the input and then output the century of that year.

For example:

```
In: 1946
Out: 20
In: 1705
Out: 18
In: 1900
Out: 19
In: 100
Out: 1
In: 2001
Out 21

```

because 1946 is in the 20th century.

Keep in mind that 2000 should be 20th century or 1900 should be in 19th century.

**Therefore, the first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.**

Any programming language is allowed and **keep your code short and sweet. :)**

**Additional Challenge: Try to also include float values**

# Answer
# 05AB1E,  4  3 bytes

-1 byte thanks to Jonathon Allan

```
т/î

```

Try it online!
> 7 votes

# Answer
# ArnoldC, 308 298 bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE x
YOU SET US UP 0
GET YOUR ASS TO MARS x
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
GET TO THE CHOPPER x
HERE IS MY INVITATION x
GET UP 99
HE HAD TO SPLIT 100
ENOUGH TALK
TALK TO THE HAND x
YOU HAVE BEEN TERMINATED

```

Try it online!

This seemed a challenge easy enough to try to write my first answer in ArnoldC...
> 34 votes

# Answer
# JavaScript, 14 bytes

```
y=>1+--y/100|0

```

Try it online
> 11 votes

# Answer
# Vim, 13 bytes

```
3I0*<Esc>*$3hd0*<C-x>*xx*<C-a>*
```
> 10 votes

# Answer
# Taxi, 1327/2433 1057/1835 bytes

Two versions here; the shortest one works but shows the result in decimal format (e.g. `20.000000` instead of `20`). I am posting both because, while the longer version is more correct, I still hope to win this code golf with the short one (it could require a little bit of tweaking, though).

**Short version**

You can test it here.

```
Go to Post Office: west, 1st left, 1st right, 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: west, 1st left, 1st right.
Pickup a passenger going to Addition Alley.
Go to Starchild Numerology: east, 1st left, 1st left, 1st left, 2nd left.
99 is waiting at Starchild Numerology.
100 is waiting at Starchild Numerology.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Narrow Path Park.
Go to Addition Alley: east, 1st left, 2nd right, 3rd right, 1st right.
Pickup a passenger going to Divide and Conquer.
Go to Narrow Path Park: north, 1st right, 1st left, 1st right.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: east, 1st right, 2nd right.
Pickup a passenger going to Trunkers.
Go to Trunkers: east, 1st right, 3rd right, 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: east, 1st right, 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: east, 1st left, 1st right.
Go to Taxi Garage: east, 1st right, 1st left, 1st right.

```

**Long version**

You can test it here.:

```
Go to Post Office: west, 1st left, 1st right, 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: west, 1st left, 1st right.
Pickup a passenger going to Addition Alley.
Go to Starchild Numerology: east, 1st left, 1st left, 1st left, 2nd left.
99 is waiting at Starchild Numerology.
100 is waiting at Starchild Numerology.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Narrow Path Park.
Go to Addition Alley: east, 1st left, 2nd right, 3rd right, 1st right.
Pickup a passenger going to Divide and Conquer.
Go to Narrow Path Park: north, 1st right, 1st left, 1st right.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: east, 1st right, 2nd right.
Pickup a passenger going to Trunkers.
Go to Trunkers: east, 1st right, 3rd right, 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: east, 1st right, 1st right.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: east, 6th right, 1st left.
Pickup a passenger going to KonKat's.
[processDigits]
Pickup a passenger going to Cyclone.
Go to Cyclone: north, 1st left, 3rd left.
Pickup a passenger going to Crime Lab.
Go to Writer's Depot: west.
"." is waiting at Writer's Depot.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: east, 1st right, 2nd right, 2nd left.
Switch to plan "notAColon" if no one is waiting.
Switch to plan "print".
[notAColon]
Go to Cyclone: west, 1st right, 1st left, 2nd right.
Pickup a passenger going to KonKat's.
Go to KonKat's: east, 2nd right, 2nd right.
Pickup a passenger going to KonKat's.
Go to Chop Suey: north, 1st right, 1st right.
Switch to plan "processDigits".
[print]
Go to KonKat's: east.
Pickup a passenger going to Post Office.
Go to Post Office: south, 3rd right, 1st left.
Go to Taxi Garage: east, 1st right, 1st left, 1st right.

```
> 10 votes

# Answer
# Brachylog, 6 bytes

```
/₁₀₀⌉₁

```

Try it online!

Just wanted to try my hand at Brachylog. Uses the "divide by 100 and ceil the result" method that many other answers use.
> 7 votes

# Answer
# , ~~19~~ ~~18~~ 16 bytes

```
1+scan()%/%99.99

```

Try it online!

Saved 1 byte thanks to digEmAll! -2 bytes thanks to JDL!
> 7 votes

# Answer
# Cubix, ~~11~~ 10 bytes

```
@)OuI('d,U

```

Try it online!

This wraps onto the cube as follows

```
    @ )
    O u
I ( ' d , U . .
. . . . . . . .
    . .
    . .

```

Watch it run

Not sure what I was thinking when I did the first one.

Excluding the path changes the general process is `I('d,)O@` \- Input integer, decrement, push 100, integer divide, increment, output integer and exit.

***Float version 16 bytes***

And since it was an interesting exercise, here's a version that will handle a float input. Try 1900, 1900.0 and 1900.1. Of course it isn't really doing floats as Cubix prefers integers and the format of the float doesn't really matter. 1900 1, 1900-1 and 1900.1 are all treated the same.

```
WBiWIUd'.(B?@,)O

```

Try it online!

And wrapped

```
    W B
    i W
I U d ' . ( B ?
@ , ) O . . . .
    . .
    . .

```

Watch it run

This one does (excluding path changes)

* `IiI` Input integer, input char (-1 for EOI or char value for seperator), Input integer
* `?` Test TOS
    + If 0 `B(`, reverse stack and decrement TOS
    + If positive `B` reverse stack
    + \** negative shouldn't happen \**
* `'d,)O@` push 100, integer divide, increment TOS, output and exit
> 6 votes

# Answer
# LOLCODE, 76 bytes

```
HAI 1.2
I HAS A x
GIMMEH x
VISIBLE QUOSHUNT OF SUM OF x AN 99 AN 100
KTHXBYE

```

Try it online!
> 6 votes

# Answer
# Hexagony, 11 bytes

```
?({!@/)d':/

```

Try it online!

Linear code (9 bytes):

```
?({d':)!@

```

Ungolfed code:

```
  ? ( {
 ! @ / )
d ' : / .
 . . . .
  . . .

```

It may be possible to save 1 or 2 bytes by using `:` to terminate (division by zero error), but I can't find out a way.
> 5 votes

# Answer
# MarioLANG, 821 807 625 595 570 386 bytes

```
;
-
)
)
+
+
(                >- >- >- >- >- >- >- >- >- >-)
(                "= "= "= "= "= "= "= "= "= "=+
>       >      >[!![!![!![!![!![!![!![!![!![!!(
"======="======"=##=##=##=##=##=##=##=##=##=##
!(![-)+<!(![(< ![ <  <  <  <  <  <  <  <  <  <<
#=#===="#=#==" #=="=="=="=="=="=="=="=="=="=="=
  >(   ! (<   >))-[!(+
  "====#=="   =====#=:
             !     <
             #====="

```

Try it online!

I'm sure this can be golfier Now this is starting to be quite golfy, though it took me a while to figure out a way to do the division in MarioLANG.

Improvements:

* Lots of bytes saved by taking advantage of the fact that Mario starts falling from the upper left corner of the code.
* Code before a fall has been placed during the fall.
* Great improvement after redesigning the division-by-10 part.

Explanation:

* First we set `a` to `INPUT` as integer and substract `1`.
* Then we set `b` to `0` and `c` equals to 2.
* Then we substract `1` from `a` 10 times, checking every step if `a` has reached `0`.
* If we successfully substract `10` from `a`, increment `b`.
* Repeat this until `a` is `0`. Now we have the result of the division in `b`.
* Substract 1 from `c` and move `b` to `a` if `b` is not `0`. After moving the value `b` is set to `0`.
* Repeat the division-by-10 operation one more time, substracting 1 from `c` again and now that `c` is `0` the program outputs the result in `b` and exits.
> 5 votes

# Answer
# Bash, ~~20~~ 19 bytes

```
echo $[($1+99)/100]

```

Try it online!

*-1 thanks to W W*
> 4 votes

# Answer
# Japt, ~~9~~ 4 bytes

*-5 from @Shaggy*

```
/L c

```

Try it online!
> 4 votes

# Answer
# SOGL V0.12, 3 bytes

```
M/U

```

Try it Here!
> 4 votes

# Answer
# C (gcc), ~~23~~ 22 bytes

```
f(i){return--i/100+1;}

```

Try it online!

-1 byte saved thanks to @luser droog

# 20 bytes

```
R;f(i){R=--i/100+1;}

```

Try it online!

-2 bytes saved thanks to @Digital Trauma

# 18 bytes

```
f(i){i=--i/100+1;}

```

Try it online!

Another -2 bytes saved thanks to @ErikF
> 4 votes

# Answer
# Stax, 5 bytes ~~(packed)~~

```
vAJ/^

```

Run and debug it

Explanation:

```
vAJ/^ Full program, implicit input
v     Decrement
 AJ   Push 100 (10<sup>2</sup>)
   /  Integer division
    ^ Increment
```
> 4 votes

# Answer
# Perl 5 `-p`, ~~18~~ 15 bytes

```
$_=1+--$_/100|0

```

Try it online!

*(-3 whole bytes, thanks to @Dom Hastings.)*

Or with `-p -MPOSIX`:

### ~~15~~ 13 bytes

```
$_=ceil$_/100

```

Try it online!

*(-2 bytes, again thanks to @Dom Hastings.)*
> 4 votes

# Answer
# Retina, 26 bytes

```
r`(.*)(.?.)
$2*X$1*
X+
_
.

```

Try it online!

My first attempt at Retina. Can probably be golfed more (though, I like the `(.?.)` babyface in this one).
> 4 votes

# Answer
# dc, 6

Assuming input and output on the top-of-stack is OK:

```
99+A0/

```

Try it online!
> 4 votes

# Answer
# Java 8, 12 bytes

```
y->~-y/100+1

```

Try it online.

**Explanation:**

```
y->     // Method with integer as both parameter and return-type
  ~-y   //  Decrease the input by 1
  /100  //  Then integer-divide it by 100
  +1    //  And then add 1

```
> 4 votes

# Answer
# GolfScript, 5 7 bytes

```
~(100/)

```

Try it online!

```
~(100/)
AAA  AA
\\\   \\
 \\\   \Increments the stack
  \\\   Divides the stack
   \\\
    \\Adds 100 to the stack
     \Decrements the stack
      Turn the input string into an int

```
> 3 votes

# Answer
# Perl 6, 13 bytes

```
(*+99)/100+|0

```

Test it

## Expanded:

```
# WhateverCode lambda
(
  *      # this is the parameter
    + 99 # add 99 to adjust the century

) / 100  # divide by 100

+| 0     # Integer bitwise-or with 0 (coerce to Int)

```
> 3 votes

# Answer
# Python 2, 18 bytes

```
lambda x:~-x/100+1

```

Try it online!
> 2 votes

# Answer
# Haskell, 16 bytes

```
(`div`100).(+99)

```

Try it online!

# 16 bytes

```
f x=div(x+99)100

```

Try it online!
> 2 votes

# Answer
# PHP, 22 bytes

```
<?=1+--$argv[1]/100|0;

```

Try it online

```
<?=ceil($argv[1]/100);

```

Try it online
> 2 votes

# Answer
# Pepe, 31 bytes

```
rEeEEeeEeeREeEREEEEeeREeEEEReEE

```

Try it online!

Basically **ceil(n/100)**.

Explanation:

```
rEeEEeeEeeREeEREEEEeeREeEEEReEE - full program

rEeEEeeEee                      - push 100 to stack B
          REeE                  - input as number to stack A. float gets rounded.
              REEEEee           - A / B, or A / 100. push in stack A.
                     REeEEE     - ceil(A)
                           ReEE - output stack A as number

```
> 2 votes

# Answer
# PHP, 19 bytes

```
<?=ceil($argn/100);

```

or

```
<?=--$argn/100+1|0;

```

Save to file, run as pipe with `-nF`.
> 2 votes

# Answer
Excel Vba, 89 bytes

```
Function GetCentury(Year As Long)
GetCentury = Mid((Year - 1) / 100, 1, 2) + 1
End Function

```

And a version with 65 bytes

```
Function C(Y As Long)
C = Mid((Y - 1) / 100, 1, 2) + 1
End Function

```

Honestly I dont even know if this is a valid entry :/
> 2 votes

# Answer
# Shakespeare Programming Language, 195 bytes

```
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen toheart!You is the sum ofa cat the quotient betweenthe sum ofyou a pig the square ofthe sum ofa big big big cat a big cat!Open heart

```

Try it online!

### Explanation:

```
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:   #Header

Listen toheart!   # Set Page to the input

# Set Page to (n-1)/(10)**2+1
You is the sum ofa cat the quotient betweenthe sum ofyou a pig the square ofthe sum ofa big big big cat a big cat!

Open heart  # Print Page's value as a number

```
> 2 votes

# Answer
# Elixir, 89 78 bytes

Not perfect but I'm just learning Elixir so code-golf it is!

```
IO.gets("")|>String.to_integer|>(&(Integer.floor_div(100,&1-1)+1)).()|>IO.puts

```

Try it online!

In a better format:

```
IO.gets("")                # Get input from terminal
|>String.to_integer        # Make it an int
|>(&(                      # Declare an anonymous function
  Integer.floor_div(100,   # Do a floored division with 100 on the bottom
     &1-1)                  # ... and the integer input minus 1 on top
  +1))                    # Add 1 to the result
  .()                      # Gotta invoke that anonymous for pipes
|>IO.puts                  # Output

```
> 2 votes

# Answer
# Pyth - ~~6~~ 7 bytes

```
.EcQ100

```

Explanation:

```
.EcQ100  Implicit print
   Q     Input
  /      Divided by
    100  100
.E       Rounded up

```

Fixed edge case
> 2 votes

# Answer
# Vyxal, ~~6~~ 4 bytes

```
‹₁ḭ›

```

Try it Online!

### Explained

```
‹₁ḭ›
‹    # decrement
 ₁ḭ  # divide floor by 100
   › # increment

```
> 2 votes

# Answer
# Gaia, 4 bytes

```
(ℍ/)

```

Pretty straightforward...

Thanks to Mr. Xcoder and this post for getting me interested in this cool but relatively unused language!

Try it online!
> 1 votes

# Answer
# MATL, 7 bytes

```
q100/kQ

```

Try it online!
> 1 votes

# Answer
# Jelly, 4 bytes

```
÷ȷ2Ċ

```

**Try it online!**
> 1 votes

# Answer
# Labyrinth, 10 bytes

```
?(_100/)!@

```

Same method as my Gaia answer.

Try it online!
> 1 votes

# Answer
# Kotlin, 19 bytes

```
{y:Int->(y+99)/100}

```

Try it online!
> 1 votes

# Answer
# Bash + coreutils, 18 bytes

```
bc<<<"($1+99)/100"

```

Try it online!
> 1 votes

# Answer
# Whitespace, ~~51~~ 50 bytes

```
[S S S T    N
_Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S S S T    N
_Push_1][T  S S T   _Subtract][S S S T  T   S S T   S S N
_Push_100][T    S T S _Integer_divide][T    S S S _Add][T   N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

-1 byte thanks to *@aschepler*.

Try it online.

**Explanation in pseudo-code:**

```
Integer n = STDIN as integer
n = n - 1
n = n integer-divided by 100
n = n + 1
Print n as integer to STDOUT

```
> 1 votes

# Answer
# Scala, 24 bytes

```
def f(a:Int)=(a-1)/100+1

```

Try it online!

# Scala, 33 bytes, with floats

```
def f(a:Float)=(Int)((a-1)/100)+1

```

Try it online!
> 1 votes

# Answer
# TeaScript, 8 bytes

```
Mc(x / h

```

Try it online!
> 1 votes

# Answer
# CJam, 6 bytes

```
(100/)

```

Try it online!
> 1 votes

# Answer
# K (oK), 7 bytes

**Solution:**

```
-_-.01*

```

Try it online!

**Explanation:**

Pretty trivial... almost looks like an emoji `(-_-)`:

```
-_-.01* / the solution
      * / multiply input by
   .01  / 0.01
  -     / negate  \
 _      / floor    - ceiling the result
-       / negate  /

```
> 1 votes

# Answer
# TI-Basic, 6 bytes

When given only one argument, `sub(` divides it by 100.

```
sub(Ans+99

```
> 1 votes

# Answer
# Octave/MATLAB, ~~15~~ 14 bytes

```
@(x)(x+49)/100

```

Try it online!

Managed to save a byte by requiring the input to be provided as an integer not a double.

This anonymous function takes an integer as an input, and returns the required value.

MATLAB/Octave when dividing integers performs rounding rather than truncation (Why Mathworks? Why?!). To convert rounding to ceil, we need to add on 49 to the number prior to division.

---

Original, perhaps uninteresting answer:

```
@(x)ceil(x/100)

```

Try it online!

Anonymous function to find the result. Just the standard `ceil()` of dividing by 100.
> 1 votes

# Answer
# Excel VBA, 13 bytes

An anonymous function that takes input from cell `[A1]` and outputs to the console.

```
?[A1-1]\100+1

```
> 1 votes

# Answer
## Python 2, 18 bytes

```
lambda x:-(x/-100)

```

Taking advantage of the fact `/` divides towards 0, we make a impromptu ceil division, assuming all inputs are positive which is the case according to the spec. Would work in Python 3 with `//` but it's golfier in Py2.

Uses `ceil(year/100)`
> 1 votes

# Answer
# Common Lisp, ~~29~~ ~~19~~ 18 bytes

```
(ceiling(/ x 100))

```

Or, if variable definitions aren't allowed, **21 bytes**

```
(ceiling(/(read)100))

```

Pretty self-explanatory, can be tested with something along these lines:

```
(setf x 1900)
(print (ceiling (/ x 100)))

```
> 1 votes

# Answer
# Ruby, 24 bytes

```
def f(n);(n-1)/100+1;end

```

Try it online!
> 1 votes

# Answer
# C (gcc), 19 bytes

```
f(x){x=x/100.+.99;}

```

Try it online!
> 1 votes

# Answer
# Vim (5 bytes)

```
99^AXx

```

This code looks for number at or on the right of the cursor, adds 99 (`^A99`) and divides it by 100 (`Xx`).

Note: `^A` is single byte (0x1 – Start Of Heading).
> 1 votes

# Answer
# MAWP, 11 bytes

```
@1A554WWPM:

```

Try it!

Saved 3 bytes thanks to @Razetime
> 1 votes

# Answer
# Go, ~~33~~ 31 bytes

```
func(y int)int{return^-y/100+1}

```

Attempt This Online!

* -2 by @Steffan: `(y-1) => ^-y`
> 1 votes

# Answer
# befunge 11 bytes

`&1-aa*/1+.@@`

* `&` read input,
* `1-` subtract one (2000 is 20th century)
* `aa*/` divide by 100
* `1+` add one
* `.` print
* `@` end
> 0 votes

# Answer
# Excel, ~~15~~ ~~21~~ ~~18~~ 13 bytes

```
=INT(99%+A1%)

```

Input is in cell `A1`
> 0 votes

# Answer
# APL (Dyalog), 6 bytes

```
⌈⎕÷100

```

My first APL answer!

Thanks to @dzaima for saving me a load of bytes!

**Try it online!**
> 0 votes

# Answer
# Charcoal, 7 bytes

```
Ｉ⌈∕Ｎ¹⁰⁰

```

Try it online! Link is to verbose version of code. Explanation:

```
    ¹⁰⁰ Literal 100
   Ｎ    Input number
  ∕     Floating-point division
 ⌈      Ceiling
Ｉ       Cast to string
        Implicitly print

```
> 0 votes

# Answer
# Noether, 7 bytes

```
I100/UP

```

**Try it online**
> 0 votes

# Answer
# Java, 19 bytes

```
y->Math.ceil(y/100)

```

Try it online.

In java, the `ceil` function helps. Input and output are both `double`.
> 0 votes

# Answer
# Python 3, 30 bytes

```
print((int(input())-1)//100+1)

```

Try it online!
> 0 votes

# Answer
# Math++, 12 bytes

```
_(.99+?/100)

```
> 0 votes

# Answer
# Lua, 21 bytes

```
print((...-1)//100+1)

```

Try it online!

I'm not sure if I can get the year as an argument, but that's how I did it.
> 0 votes

# Answer
**EXCEL, 17 bytes**

`A1` as input

`=ROUNDUP(A1/100,)`
> 0 votes

# Answer
# Brain-Flak, 68 bytes

```
({}[()])<>((((((()()()){}){}){}()){}){})({<(({})){({}[()])<>}{}>()})

```

Try it online!

Pushing the number `100` is longer than the div algorithm itself! Calculates `(n-1)/100+1`.
> 0 votes

# Answer
# brainfuck, 147 bytes

```
,>,>,>,>>++++++++[-<++++++>]<[->+<<-<-<-<->>>>]<[-<+>]<[<+>[-]]<[->+>+<<]>>>++++++++++[-<->]+<[<[-<+>]>>-<[-]]>[<<<<+>>>>-]>[-<<<<<+>+>>>>]<<<<<.>.

```

Try it online!

# Explanation

```
,>,>,>,>                 input
>++++++++[-<++++++>]     store a '0'
<[- >+<                  save '0'
 <-<-<-<->>>>            subtract '0'
]
<[-<+>]                  move 10^0 to 10^1
<[                       check if 10^1 has a non-zero value
 <+>                     increment 10^2
 [-]                     exit
]
<[->+>+<<]               copy 10^2 twice
>>>
++++++++++               store a ten
[-<->]                   subtract ten
+                        flag for if check
<                        if zero then carry
[                        not zero
 <[-<+>]                 put 10^2 one to the left
 >>-<[-]
]>
[                        it was zero so carry
 <<<<+>>>>-
]
>[-<<<<<+>+>>>>]<<<<<.>. print

```
> 0 votes

# Answer
# JavaScript, 14 bytes

```
n=>n/100+.99|0

```

Since the century is roughly `year/100 + 1`, minus an offset of 1 year, it can be calculated like `(n+99)/100`. This is then rounded down to an integer in the last two bytes.
> 0 votes

# Answer
# Ruby, 14 bytes

```
->n{~-n/100+1}

```

Try it online!

I think it's squeezed as much as possible. I would love to see if anyone has any clever tricks to make this smaller.
> 0 votes

# Answer
# Ruby, 16 bytes

```
->i{(i-1)/100+1}

```
> 0 votes

# Answer
# Swift 4, 18 bytes

```
print((n-1)/100+1)

```

Try it online!

`n` is the input of the program
> 0 votes

# Answer
# x86\_64 machine language on Linux, 12 bytes

```
0:   97                      xchg   %eax,%edi
1:   ff c8                   dec    %eax
3:   6a 64                   pushq  $0x64
5:   59                      pop    %rcx
6:   99                      cltd
7:   f7 f9                   idiv   %ecx
9:   ff c0                   inc    %eax
b:   c3                      retq

```

Try it online!
> 0 votes

# Answer
# Rockstar, 51 bytes

A nice easy one to finish the week after this monstrosity!

```
listen to Y
let Y be-1
let Y be/100
turn up Y
say Y

```

Try it here (Code will need to be pasted in)
> 0 votes

# Answer
# J-uby, 18 bytes

```
:pred|~:/&100|:+&1

```

`:+&-1` is equivalent to `:pred` but IMO `:pred` is prettier. Alas `:+&1` is shorter than `:succ`.

Attempt This Online!
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
ɦ/ṃ

```

Attempt This Online!

#### Explanation

```
ɦ/ṃ  #      input
ɦ    #              100
 /   #            /
  ṃ  # ceil(           )
     # Implicit output

```
> 0 votes

# Answer
# Ly, 7 bytes

```
'c+SppJ

```

Try it online!

This uses the `(N+99)` trick other code uses to get the right century for `xx00` years. After that it converts the result to a string and prints the first two digits.

```
'c       - push 99 onto the stack
  +      - add number on STDIN to 99
   S     - split number to digits
    pp   - delete two least significant digits
      J  - recombine the remaining two digits into a number

```

The stack prints as number by default when the program exits
> 0 votes

---
Tags: code-golf
---


title: RADD decomposition of an integer

text:
# Question
Title: RADD decomposition of an integer
## Introduction

The \\$RADD(n)\\$ operation is defined as the sum of \\$n + \[\\$ the number whose decimal representation are the decimal digits of \\$n\\$ in reverse order \\$\]\\$, see A004086. After reversal, trailing zeros are lost. See Reverse-Then-Add Sequence and A056964.

Not all numbers can be represented as the result of a \\$RADD\\$ operation.

## Examples

\\$RADD(11) = 11 + 11 = 22\\ RADD(23) = 23 + 32 = 55\\ RADD(70) = 70 + 7 = 77\\ RADD(85) = 85 + 58 = 143\\ RADD(1100)= 1100 + 11 = 1111\\$

## Task

We are looking for a method that determines for a given number \\$m\\$, whether it can be represented with \\$RADD\\$, and if this is the case, then determines an argument \\$n\\$ such that \\$m = RADD(n)\\$, symbolically \\$n = RADD^{-1}(m)\\$

As a convention, the larger of the two summands shall be used as result, e.g., \\$RADD^{-1}(55) = 32, RADD^{-1}(143) = 85\\$

If more than one decomposition is possible, there is no preferred choice which one is used for the output.

Since the problem comes from the OEIS sequence A356648, only square numbers \\$s=n^2\\$ should be considered as a target.

## Challenge

Write a function or a program that takes an integer \\$n\gt0\\$ as input and returns the \\$RADD\\$ decompositions \\$RADD^{-1}(k\_{i}^2)\\$ of as many as possible further distinct square numbers \\$k\_{i}^2 \ge n^2\\$ as the result, such that there are no numbers \\$k'\\$ with \\$k\_{i}\<k'\<k\_{i+1}\\$ whose squares \\$k'^2\\$ are also \\$RADD\\$-decomposable.

As \\$n\\$ increases, the obvious trivial method of looping through all candidates may become infeasible.

## Winning criterion

The program that delivers the most consecutive terms represented by their decompositions after \\$n=1101111\\$ \\$(1101111^2 = 220005934299 + 992439500022)\\$ in a running time of \\$300\\$ s wins. If only one term is found, the combined running time to scan the range up to this term and to find its decomposition counts.

## Tests

With \\$R2(n) := RADD^{-1}(n^2)\\$

```
    n = {2, 4, 11, 22, 25, 33, 101, 121, 141, 202, 222, 264, 303, 307, 451, 836, 1001}
    R2(2) = 2, (2^2 = 2 + 2)
    R2(22) = 341, (22^2 = 484 = 143 + 341)

```

for all numbers \\$n\_i\le 1001\\$ not in the list no \\$RADD\\$ decomposition exists.

* Range \\$10^5\cdots 2\times 10^5\\$

```
n = {100001, 101101, 102201, 103801, 105270, 109901, 110011, 111111, 111221, 112211, 120021, 121121, 122221, 125092, 125129, 133431, 138259, 148489, 161619, 165269, 171959, 200002}

```

are the only numbers in this range for which \\$RADD\\$ decompositions exist.

* Some larger examples

```
n = 386221, n^2 = 149166660841 = 100166999840 + 48999661001, R2(386221)= 100166999840
n = 476311, n^2 = 226872168721 = 130002968690 + 96869200031, R2(476311) = 130002968690
n = 842336, n^2 = 709529936896 = 109600929995 + 599929006901, R2(842336) = 599929006901

```

# Answer
> 10 votes
# C++11 (gcc), O(log(n))

This algorithm can check, if a number n has a RADD-decomp and calculate the decomp in O(D)=O(log(n)), where D is the number of digits. It also includes a pre-test, with shorter loop.
In this way, a large range can be scanned without gaps:

TOTAL COUNT IN \[1:8589934591\]: 2219
(There are 2219 \\$\ n\in\[1:2^{33}-1\]\\$ such that \\$n^2\\$ has a RADD decomposition)
Took 153s on my pc.

The core routine uses byte-arrays to process large numbers.
With the new approach, squares are not explicitly calculated. However, adding odd numbers to get the next squares still creates some overhead. But it runs faster overall without conversion from int to byte-array.

Try online

```
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#define FRC_INLINE __attribute__((always_inline)) inline

#include <iostream>
using std::cout;

typedef uint64_t intI;
typedef __uint128_t intO;

//decimal digit
//to represent a number n, all 'digit n[i]' shall be in [0:9]
//as a temp in a calculation it may also be negative
typedef signed char digit;

//RADD pre-test
//n is an array containing L decimal digits
//returns true, if for a given n there is an R, s.t. n=R+reverse_decimal(R)
//returns false in many cases where no RADD-decomp exists
//error rate < 0.003% for n in [1:2^32]
//running time is in O(L)
template<bool check1=true>
FRC_INLINE bool preTestRADD(const digit* n, int L)
{
    if (L < 1) return false;
    int N = L-1;

    if (n[N] == 1 && check1) {
        if (n[0] == 1)
            if (preTestRADD<false>(n, L)) return true;
        --N;
    }

    for (int d = 0; N-d-d > 0; ++d) {
        digit x = n[d]-n[N-d];
        if (!(x==0 || x==1 || x==9 || x==-1 || x==-9)) return false;
    }

    return true;
}

//calc RADD-decomposition
//n is an array containing L decimal digits
//checks for a given n, if there is an R, s.t. n=R+reverse_decimal(R)
//if yes, it determines the highest such R and returns the digit count of R
//returns 0, if no RADD-decomp exists (then R is undefined)
//running time is in O(L)
template<bool check1=true>
FRC_INLINE int calcRADD(digit* R, const digit* n, int L)
{
    if (L < 1) return 0;
    int N = L-1;
    digit cri = 0, cro = 0;

    if (n[N] == 1 && check1) {
        if (n[0] == 1) {
            int L2;
            if (L2 = calcRADD<false>(R, n, L)) return L2;
        }
        --N;
        cro = 1;
    }

    int d = 0;

    for (; N-d-d > 0; ++d) {
        switch (n[d]-n[N-d]) {
            case -9: {
                if (!cri || cro) return 0;
                R[d] = 0;
                R[N-d] = 9;
                break;
            }
            case -1: {
                if (cri) return 0;
                if (cro) {
                    R[d] = n[d]+1;
                    R[N-d] = 9;
                } else {
                    R[d] = 0;
                    R[N-d] = n[d];
                }
                cri = cro;
                cro = 1;
                break;
            }
            case 0: {
                if (cro) {
                    R[d] = n[d]-cri+1;
                    if (R[d] > 9) return 0;
                    R[N-d] = 9;
                } else {
                    R[N-d] = n[d]-cri;
                    if (R[N-d] < 0) return 0;
                    R[d] = 0;
                }
                std::swap(cri,cro);
                break;
            }
            case 1: {
                if (!cri) return 0;
                if (cro) {
                    R[d] = n[N-d]+1;
                    R[N-d] = 9;
                } else {
                    R[d] = 0;
                    R[N-d] = n[N-d];
                }
                cri = cro;
                cro = 0;
                break;
            }
            case 9: {
                if (cri || !cro) return 0;
                R[d] = 0;
                R[N-d] = 9;
                break;
            }
            default: {
                return 0;
            }
        }
    }

    if (!(N-d-d)) {
        if ((n[d] & 1) != cri) return 0;
        R[d] = n[d]/2 + 5*cro;
        return N+1;
    }

    if (cro != cri) return 0;
    return N+1;
}

constexpr int MAX_DIGITS = 40;

FRC_INLINE int getDigits(digit d[MAX_DIGITS], intO n)
{
    int L = 0;
    for (; L < MAX_DIGITS; ++L){
        if (n <= 0xFFFFFFFFFFFFFFFF) break;
        d[L] = n % 10;
        n /= 10;
    }
    intI nt = (intI)n;
    for (; L < MAX_DIGITS; ++L){
        if (!nt) break;
        d[L] = nt % 10;
        nt /= 10;
    }
    return L;
}

//returns 0, if n^2 has no RADD-decomp
//otherwise it returns the highest R with n^2=R+reverse_decimal(R)
//running time is in O(log(n))
//faster for single numbers / small ranges
FRC_INLINE intO RADD2(intI n)
{
    digit in[MAX_DIGITS];
    digit out[MAX_DIGITS];

    intO n2 = (intO)n*n;
    intO nt = n2;

    int L = 0;
    for (; L < MAX_DIGITS; ++L){
        if (nt <= 0xFFFFFFFFFFFFFFFF) break;
        in[L] = nt % 10;
        nt /= 10;
    }
    intI ntt = (intI)nt;
    for (; L < MAX_DIGITS; ++L){
        if (!ntt) break;
        in[L] = ntt % 10;
        ntt /= 10;
    }

    if (!preTestRADD(in, L)) return 0;

    int Lout = calcRADD(out, in, L);
    if (!Lout) return 0;

    nt = out[Lout-1];
    for (int l = Lout-2; l >= 0; --l) {
        nt *= 10;
        nt += out[l];
    }

    if (n <= 0xFFFFFFFF)
    {
        std::cout << n << "-> " << (intI)n2 << " R: " << (intI)nt << "\n";
    } else {
        std::cout << n << "-> ";
        for (int l = L-1; l >= 0; --l) std::cout << (char)(in[l]+'0');
        std::cout << " R: ";
        for (int l = Lout-1; l >= 0; --l) std::cout << (char)(out[l]+'0');
        std::cout << "\n";
    }

    return nt;
}

//scans range [A:B]
//no explicit calculation of squares
//faster for bigger ranges
FRC_INLINE int scan(intI A, intI B)
{
    static digit n2[MAX_DIGITS];
    static digit R2[MAX_DIGITS];
    static digit step[MAX_DIGITS];

    for (int i=0; i<MAX_DIGITS; ++i) {
        step[i] = 0; n2[i] = 0;
    }

    intI n = A;
    int n2L = getDigits(n2,(intO)n*n);
    int stpL = getDigits(step,2*(intO)n-1);

    int cnt = 0;
    for (;;++n) {
        if (!n) return cnt;

        int R2L = 0;
        if (preTestRADD(n2, n2L))
            R2L = calcRADD(R2, n2, n2L);

        if (R2L) {
            ++cnt;
            cout << n << "-> ";
            for (int l = n2L-1; l >= 0; --l) cout << (char)(n2[l]+'0');
            cout << " R: ";
            for (int l = R2L-1; l >= 0; --l) cout << (char)(R2[l]+'0');
            cout << "\n";
        }

        if (n >= B) return cnt;

        //n2 <- next square
        int cs;
        if (cs = ((*step+=2)>9 ? 1 : 0)) *step = 1;
        digit cn = (*n2+=*step)>9 ? 1 : 0;
        *n2 -= 10*cn;
        for (int i = 1; i < MAX_DIGITS; ++i) {
            if (i >= stpL && !cs && !cn) break;
            if (cs = ((step[i]+=cs)>9 ? 1 : 0)) step[i] = 0;
            cn = (n2[i]+=step[i]+cn)>9 ? 1 : 0;
            n2[i] -= 10*cn;
        }
        if (step[stpL]) ++stpL;
        if (n2[n2L]) ++n2L;
    }
}

constexpr intI SCAN_START = 1;
//constexpr intI SCAN_START = 0xFFFFFFFF;

//constexpr intI SCAN_STOP = 1000000000;
constexpr intI SCAN_STOP = 0x1FFFFFFFF;

int main() {
    int cnt = scan(SCAN_START,SCAN_STOP);

    /*int cnt = 0;
    for (intI n = SCAN_START; n <= SCAN_STOP; ++n) {
        if (!n) break;

        intO R2 = RADD2(n);

        if (R2) ++cnt;
    }*/

    cout << "TOTAL COUNT IN [" << SCAN_START << ":" << SCAN_STOP << "]: " << cnt << std::endl;
    return 0;
}

```

# Answer
> 2 votes
# Haskell, 4 s

```
sums[a]=[[a]]
sums(a:b:c)=map(a:)(sums(b:c))++map((a-1):)(filter(const(a>0))$sums((10+b):c))

pick[]=[]
pick[c]=[div c 2]
pick(a:b)=min 9a:pick(init b)++[max 0(a-9)]

radd n=n+(read.reverse.show)n
iradd n=
 (\s->case s of[]->0;_->(read.concat.map show.pick.head)s).
 filter(\x->x==reverse x).map(dropWhile(==0)).sums.
 map(read.(:"")).show$n

main=print$take 1[(n,n2,i,n2-i)|n<-[1101112..],let n2=n^2,let i=iradd n2,i>0,radd i==n2]

```

Try it online!

# Answer
> 2 votes
26496 in 51min

Unordered but should cover \[0,10^14)

```
#include <vector>
#include <set>
#include <bitset>
#include <iostream>
#include <math.h>

//  Sebastian

typedef uint64_t intI;
typedef __uint128_t intO;

std::set<intI> outted;

typedef signed char digit;
template<bool check1=true>
inline bool preTestRADD(const digit* n, int L)
{
    if (L < 1) return false;
    int N = L-1;

    if (n[N] == 1 && check1) {
        if (n[0] == 1)
            if (preTestRADD<false>(n, L)) return true;
        --N;
    }

    for (int d = 0; N-d-d > 0; ++d) {
        digit x = n[d]-n[N-d];
        if (!(x==0 || x==1 || x==9 || x==-1 || x==-9)) return false;
    }

    return true;
}template<bool check1=true>
inline int calcRADD(digit* R, const digit* n, int L)
{
    if (L < 1) return 0;
    int N = L-1;
    digit cri = 0, cro = 0;

    if (n[N] == 1 && check1) {
        if (n[0] == 1) {
            int L2;
            if (L2 = calcRADD<false>(R, n, L)) return L2;
        }
        --N;
        cro = 1;
    }

    int d = 0;

    for (; N-d-d > 0; ++d) {
        switch (n[d]-n[N-d]) {
            case -9: {
                if (!cri || cro) return 0;
                R[d] = 0;
                R[N-d] = 9;
                break;
            }
            case -1: {
                if (cri) return 0;
                if (cro) {
                    R[d] = n[d]+1;
                    R[N-d] = 9;
                } else {
                    R[d] = 0;
                    R[N-d] = n[d];
                }
                cri = cro;
                cro = 1;
                break;
            }
            case 0: {
                if (cro) {
                    R[d] = n[d]-cri+1;
                    if (R[d] > 9) return 0;
                    R[N-d] = 9;
                } else {
                    R[N-d] = n[d]-cri;
                    if (R[N-d] < 0) return 0;
                    R[d] = 0;
                }
                std::swap(cri,cro);
                break;
            }
            case 1: {
                if (!cri) return 0;
                if (cro) {
                    R[d] = n[N-d]+1;
                    R[N-d] = 9;
                } else {
                    R[d] = 0;
                    R[N-d] = n[N-d];
                }
                cri = cro;
                cro = 0;
                break;
            }
            case 9: {
                if (cri || !cro) return 0;
                R[d] = 0;
                R[N-d] = 9;
                break;
            }
            default: {
                return 0;
            }
        }
    }

    if (!(N-d-d)) {
        if ((n[d] & 1) != cri) return 0;
        R[d] = n[d]/2 + 5*cro;
        return N+1;
    }

    if (cro != cri) return 0;
    return N+1;
}inline intO RADD2(intI n, intO& n2)
{
    constexpr int MAX_DIGITS = 0x40;
    digit in[MAX_DIGITS];
    digit out[MAX_DIGITS];
        n2 = (intO)n*n;

    intO nt = n2;

    int L;
    for (L = 0; L < MAX_DIGITS; ++L){
        if (nt <= 0xFFFFFFFFFFFFFFFF) break;
        in[L] = nt % 10;
        nt /= 10;
    }
    uint64_t ntt = (uint64_t)nt;
    for (; L < MAX_DIGITS; ++L){
        if (!ntt) break;
        in[L] = ntt % 10;
        ntt /= 10;
    }

    if (!preTestRADD(in, L)) return 0;

    int Lout = calcRADD(out, in, L);
    if (!Lout) return 0;

    nt = out[Lout-1];
    for (int l = Lout-2; l >= 0; --l) {
        nt *= 10;
        nt += out[l];
    }

if (outted.count(n)) return 0; outted.insert(n);

    if (n <= 0xFFFFFFFF)
    {
        std::cout << n << " -> " << (uint64_t)n2 << " R: " << (uint64_t)nt << std::endl;
    } else {
        std::cout << n << " -> ";
        for (int l = L-1; l >= 0; --l) std::cout << (char)(in[l]+'0');
        std::cout << " R: ";
        for (int l = Lout-1; l >= 0; --l) std::cout << (char)(out[l]+'0');
        std::cout << std::endl;
    }

    return nt;
}

int cnt;

void call(intI n) {
    intO n2;
    intO R2 = RADD2(n, n2);
    if (R2) cnt++;
}

typedef unsigned int uint;
typedef unsigned long u2int;
typedef __uint128_t u4int;

std::vector<uint> ves[11111119];
//std::set<u2int> ved[10000007];

constexpr u2int pow10l(int n) {
    return n?pow10l(n-1)*10:1;
}
constexpr u2int pow10g(int n) {
    return n?pow10g(n-1)*10+1:0;
}

template<int P, int Q, int N>
struct ragebase { static
void rage(u2int p, uint q) {
    if (ves[pow10g(Q)+q% pow10l(Q)].empty()) return;
    //#pragma nounroll
    for (int i=Q==0?1:0; i<19; ++i) {
        ragebase<P-1, Q+1, N>::rage (p+i*pow10l(P-1), q+i*pow10l(Q));
    }
}};
template<int Q, int N>
struct ragebase<0,Q,N> { static
void rage (u2int p, uint q) { //if (p==161) fprintf(stderr, "%lu/%u\n", p, q);
    q = q % pow10l(N);
    std::vector<uint>& r = ves[pow10g(N)+q];
    //std::set<u2int>& y = ved[q];
    if (r.empty()) return;
    {uint pB = sqrtl(p*pow10l(N)/1000);
    uint pL = pB-1, pR = pB+1;
    if (pL==-1) pL=0;
    for (uint i=pL; i<=pR; ++i) {
        //if (y.count(i)) continue; y.insert(i);
        for (uint j: r) {
            call ( i*pow10l(N)+j);
        }
    }}
    {uint pB = sqrtl(p*pow10l(N)/100);
    uint pL = pB-1, pR = pB+1;
    if (pL==-1) pL=0;
    for (uint i=pL; i<=pR; ++i) {
        //if (y.count(i)) continue; y.insert(i);
        for (uint j: r) {
            call ( i*pow10l(N)+j);
        }
    }}
    {uint pB = sqrtl(p*pow10l(N)/10);
    uint pL = pB-1, pR = pB+1;
    if (pL==-1) pL=0;
    for (uint i=pL; i<=pR; ++i) {
        //if (y.count(i)) continue; y.insert(i);
        for (uint j: r) {
            call ( i*pow10l(N)+j);
        }
    }}
    {uint pB = sqrtl(p*pow10l(N)/1);
    uint pL = pB-1, pR = pB+3;
    if (pL==-1) pL=0;
    for (uint i=pL; i<=pR; ++i) {
        //if (y.count(i)) continue; y.insert(i);
        for (uint j: r) {
            call ( i*pow10l(N)+j);
        }
    }}

}};
//template<int P, int Q, int N>
//using rage = ragebase<P,Q,N>::rage;

template<int N>
void run() {
    std::cerr << N << ' ' << clock() << '\n';
    //for (int i=0; i<pow10l(N); ++i) ves[i].clear();
    //for (int i=0; i<pow10l(N); ++i) ved[i].clear();
    for (u2int i=0; i<pow10l(N); ++i) ves[pow10g(N)+i*i%pow10l(N)].push_back(i);
    std::cerr << N << ' ' << clock() << '\n';

    ragebase<N,0,N>::rage(0,0);
}

int main() {
    run<0>();
    run<1>();
    run<2>();
    run<3>();
    run<4>();
    run<5>();
    run<6>();
    run<7>();
}

```

Try it online!

---

Old answer:

C++ (gcc), 554 in 76s

```
#include <stdio.h>
#include <math.h>
typedef unsigned long xint;

constexpr xint pow10(int n) {
    return n?pow10(n-1)*10:1;
}

#define L(m,n,y) for(i##n=i##m; i##n<pow10(y)*19; i##n+=pow10(y)+pow10(n))
#define Lz(m,n,y) for(i##n=i##m+pow10(y)+pow10(n); i##n<pow10(y)*19; i##n+=pow10(y)+pow10(n))
#define L0(n) for(i##n=0; i##n<pow10(n)*19; i##n+=pow10(n)*2)
#define L1(n) for(i##n=0; i##n<pow10(n)*11*19; i##n+=pow10(n)*11)
#define H(s) { t=sqrtl(i0); if (t*t==i0) printf("%lu: %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n", i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10); }

#define M1(n) Lz(1,0,n) H()
#define M2(n) L(2,1,n-1) M1(n)
#define M3(n) L(3,2,n-2) M2(n)
#define M4(n) L(4,3,n-3) M3(n)
#define M5(n) L(5,4,n-4) M4(n)
#define M6(n) L(6,5,n-5) M5(n)
#define M7(n) L(7,6,n-6) M6(n)
#define M8(n) L(8,7,n-7) M7(n)
#define M9(n) L(9,8,n-8) M8(n)

#define P(n) L0(n) M##n(2*n)  L1(n) M##n(2*n+1)

int main() {

        run();
    xint i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0, i9=0, i10=0, t;

    //L0(1) Lz(1,0,2) H()

    //L1(1) Lz(1,0,3) H()

    P(1)P(2)P(3)P(4)P(5)

}

```

```
}

```

Try it online!

Search all numbers that is A+rev(A). Slower than creent record but I still post it

# Answer
> 0 votes
# Scala

I was trying to rewrite @Roman Czyborra's Haskell solution in scala.

\\$ \color{red}{\text{But the Scala code outputs None}}\\$

Any help would be appreciated.

TIO

```
object Main {

  def sums(lst: List[Int]): List[List[Int]] = lst match {
    case Nil      => Nil
    case a :: Nil => List(List(a))
    case a :: rest =>
      sums(rest)
        .flatMap(l => List((a :: l), (a - 1) :: l))
        .filter(l => l.head > 0)
  }

  def pick(lst: List[Int]): List[Int] = lst match {
    case Nil      => Nil
    case c :: Nil => List(c / 2)
    case a :: rest =>
      val updatedRest = pick(rest.init)
      (math.min(9, a) :: updatedRest) :+ math.max(0, a - 9)
  }

  def radd(n: Int): Int = n + (n.toString.reverse.toInt)

  def iradd(n: Int): Int = {
    val sumsList = sums(n.toString.map(_.asDigit).toList)
    val filteredList =
      sumsList.filter(x => x == x.reverse).map(_.dropWhile(_ == 0))
    if (filteredList.isEmpty) 0
    else pick(filteredList.head).mkString("").toInt
  }

  def main(args: Array[String]): Unit = {
    val nums = Stream.from(1101112).map(n => (n, n * n))
    val output = nums.collectFirst {
      case (n, n2) => {
        val i = iradd(n2)
        if (i > 0 && radd(i) == n2)
          Some((n, n2, i, n2 - i))
        else None
      }
    }.flatten
    println(output)
  }

}

```

---
Tags: math, integer, fastest-code, fastest-algorithm
---