Home » Even-Odd Reversed Squares

Even-Odd Reversed Squares

Find first 50 numbers (at least 2 digits) where 1. the number and its reversed number both are perfect squares. 2. the number is even but reversed number is odd OR the number is odd but reversed number is even List Even and Odd numbers in two separate columns. Ex. 144 => the number 144 and its reversed number 441 both are perfect squares. 144 is even but 441 is odd.

📌 Challenge Details and Links
ExcelBI Excel Challenge Number: 678
Challenge Difficulty: ⭐️⭐️
📥Download Sample File
📥Link to the solutions on LinkedIn

Solving the challenge of Even-Odd Reversed Squares with Power Query

Power Query solution 1 for Even-Odd Reversed Squares, proposed by Seokho MOON:
let
  Fun = each [
    A = Number.From(Text.Reverse(Text.From(_ * _))), 
    B = Number.Mod(Number.Sqrt(A), 1) = 0, 
    C = Number.Mod(_, 2) + Number.Mod(A, 2) = 1, 
    D = {B and C, Number.Mod(_, 2)}
  ][D], 
  Cols = List.Generate(
    () => [N = 1, R = {{}, {}}], 
    each List.Count(List.Combine([R])) < 51, 
    each [
      N = [N] + 1, 
      R = 
        if not Fun(N){0} then
          [R]
        else if Fun(N){1} = 0 then
          {[R]{0} & {N * N}, [R]{1}}
        else
          {[R]{0}, [R]{1} & {N * N}}
    ], 
    each [R]
  ), 
  Res = Table.FromColumns(List.Last(Cols), {"Even", "Odd"})
in
  Res
Power Query solution 2 for Even-Odd Reversed Squares, proposed by Peter Krkos:
let
  L = List.Transform(List.Numbers(1, 1000000), each Number.Power(_, 2)), 
  First50 = List.FirstN(
    List.Select(
      L, 
      each 
        let
          a = Number.From(Text.Reverse(Text.From(_))), 
          b = Number.Sqrt(a)
        in
          List.AllTrue(
            {
              List.AnyTrue(
                {Number.IsEven(_) and Number.IsOdd(a), Number.IsEven(a) and Number.IsOdd(_)}
              ), 
              b = Number.IntegerDivide(b, 1)
            }
          )
    ), 
    50
  ), 
  Tbl = Table.FromColumns(
    {List.Select(First50, Number.IsEven), List.Select(First50, Number.IsOdd)}, 
    type table [Even = Int64.Type, Odd = Int64.Type]
  )
in
  Tbl
Power Query solution 3 for Even-Odd Reversed Squares, proposed by Maciej Kopczyński:
let
  lst = List.Numbers(1, 10e7), 
  tbl = Table.FromList(lst, Splitter.SplitByNothing(), {"Number"}), 
  tblAc = Table.AddColumn(
    tbl, 
    "Params", 
    each [
      NumberRev = Number.FromText(Text.Reverse(Text.From(_[Number]))), 
      Sqrt1 = (Number.Mod(Number.Sqrt(_[Number]), 1) = 0), 
      Sqrt2 = (Number.Mod(Number.Sqrt(NumberRev), 1) = 0), 
      xor = Number.BitwiseXor(
        Number.From(Number.IsEven(_[Number])), 
        Number.From(Number.IsEven(NumberRev))
      )
        = 1, 
      flag = (Sqrt1 = true) and (Sqrt2 = true) and (xor = true)
    ]
  ), 
  tblExp = Table.ExpandRecordColumn(tblAc, "Params", {"flag"}, {"flag"}), 
  sR = Table.SelectRows(tblExp, each ([flag] = true)), 
  firstNRows = Table.FirstN(sR, n)[Number], 
  evens = List.Select(firstNRows, each Number.Mod(_, 2) = 0), 
  odds = List.Select(firstNRows, each Number.Mod(_, 2) <> 0), 
  maxLength = List.Max({List.Count(evens), List.Count(odds)}), 
  evensPadded = List.Combine({evens, List.Repeat({null}, maxLength - List.Count(evens))}), 
  oddsPadded = List.Combine({odds, List.Repeat({null}, maxLength - List.Count(odds))}), 
  result = Table.FromColumns({evensPadded, oddsPadded}, {"Even", "Odd"})
in
  result

Solving the challenge of Even-Odd Reversed Squares with Excel

Excel solution 1 for Even-Odd Reversed Squares, proposed by Bo Rydobon 🇹🇭:
=LET(n,SEQUENCE(3100,,10)^2,s,SEQUENCE(,7),m,BYROW(REPT(LEFT(RIGHT(n,s)),s<=LEN(n)),CONCAT)^0.5,y,ISODD(n+m)*(MOD(m,1)=0),IFNA(HSTACK(FILTER(n,y*ISEVEN(n)),FILTER(n,y*ISODD(n))),""))
Excel solution 2 for Even-Odd Reversed Squares, proposed by Rick Rothstein:
=LET(n,
    SEQUENCE(
        3100,
        ,
        4
    )^2,
    r,
    MAP(
        n,
        LAMBDA(
            x,
            CONCAT(
                MID(
                    x,
                    10-SEQUENCE(
                        9
                    ),
                    1
                )
            )
        )
    ),
    q,
    r^0.5,
    f,
    FILTER(n,
    (MOD(
        n,
        2
    )<>MOD(
        r,
        2
    ))*(q=INT(
        q
    ))),
    IFNA(
        HSTACK(
            FILTER(
                f,
                ISEVEN(
                    f
                )
            ),
            FILTER(
                f,
                ISODD(
                    f
                )
            )
        ),
        ""
    ))
Excel solution 3 for Even-Odd Reversed Squares, proposed by John V.:
=IFNA(DROP(REDUCE(0,{1,0},LAMBDA(a,v,LET(s,SEQUENCE,i,s(1546,,9+v,2)^2,HSTACK(a,FILTER(i,MOD(MAP(i,LAMBDA(x,CONCAT(MID(x,8-s(7),1))^0.5)),2)=v))))),,1),"")
Excel solution 4 for Even-Odd Reversed Squares, proposed by Timothée BLIOT:
=LET(
    A,
    SEQUENCE(
        3100,
        ,
        10
    )^2,
    B,
    MAP(
        A,
        LAMBDA(
            x,
             --CONCAT(
                 MID(
                     x,
                      LEN(
                          x
                      )+1-SEQUENCE(
                          LEN(
                          x
                      )
                      ),
                     1
                 )
             )
        )
    ),
    C,
    FILTER(
        A,
        INT(
            B^0.5
        )=B^0.5
    ),
     D,
    FILTER(
        B,
        INT(
            B^0.5
        )=B^0.5
    ),
    IFNA(
        HSTACK(
            FILTER(
                C,
                ISEVEN(
                    C
                )*ISODD(
                    D
                )
            ),
            FILTER(
                C,
                ISODD(
                    C
                )*ISEVEN(
                    D
                )
            )
        ),
        ""
    )
)
Excel solution 5 for Even-Odd Reversed Squares, proposed by Hussein SATOUR:
=LET(a,
    SEQUENCE(
        3100,
        ,
        10
    ),
    b,
    a^2,
    c,
    MAP(
        b,
        LAMBDA(
            x,
            SQRT(
                --CONCAT(
                    MID(
                        x,
                        SEQUENCE(
                            10,
                            ,
                            10,
                            -1
                        ),
                        1
                    )
                )
            )
        )
    ),
    d,
    FILTER(b,
    (c=INT(
        c
    ))+(ISODD(
        a
    )=ISEVEN(
        c
    ))=2),
    IFNA(
        HSTACK(
            FILTER(
                d,
                ISEVEN(
                    +d
                )
            ),
            FILTER(
                d,
                ISODD(
                    +d
                )
            )
        ),
        ""
    ))
Excel solution 6 for Even-Odd Reversed Squares, proposed by Duy Tùng:
=LET(S,ISEVEN,D,ISODD,a,TAKE(TOCOL(MAP(SEQUENCE(3500,,10)^2,LAMBDA(x,LET(a,--CONCAT(MID(x,LEN(x)+1-SEQUENCE(LEN(x)),1)),x/AND(S(x)=D(a),MOD(SQRT(a),1)=0)))),3),50),IFNA(HSTACK(FILTER(a,S(a)),FILTER(a,D(a))),""))
Excel solution 7 for Even-Odd Reversed Squares, proposed by Sunny Baggu:
=LET(
 _s, SEQUENCE(3300, , 9),
 _e1, LAMBDA(a, CONCAT(MID(a, LEN(a) + 1 - SEQUENCE(LEN(a)), 1)) + 0),
 _a, _s ^ 2,
 _b, MAP(_a, LAMBDA(a, _e1(a))),
 _c1, ISODD(-_a) * ISEVEN(-_b),
 _c2, ISODD(-_b) * ISEVEN(-_a),
 _c3, (SQRT(_a) = INT(SQRT(_a))) * (SQRT(_b) = INT(SQRT(_b))),
 _num, TAKE(FILTER(_a, (_c1 + _c2) * _c3), 50),
 IFNA(
 HSTACK(FILTER(_num, ISEVEN(_num)), FILTER(_num, ISODD(_num))),
 ""
 )
)
Excel solution 8 for Even-Odd Reversed Squares, proposed by LEONARD OCHEA 🇷🇴:
=LET(S,SEQUENCE,P,ISEVEN,I,ISODD,F,FILTER,n,S(3100)^2,x,BYROW(MID(n,S(,7,7,-1),1),CONCAT)^0.5,b,(x=INT(x))*((I(x^2)*P(n))+(P(x^2)*I(n)))*IF(P(n),1,2),IFNA(HSTACK(F(n,b=1),F(n,b=2)),""))
Excel solution 9 for Even-Odd Reversed Squares, proposed by Anshu Bantra:
=LET(
 n,
     SEQUENCE(
         3100,
          ,
          10
     ) ^ 2,
    
 r,
     MAP(
         n,
          LAMBDA(
              x,
               --CONCAT(
                   MID(
                       x,
                        SEQUENCE(
                            LEN(
                                x
                            ),
                             ,
                             LEN(
                                x
                            ),
                             -1
                        ),
                        1
                   )
               )
          )
     ),
    
 s,
     FILTER(
 n,
    
 (ISEVEN(
     n
 ) <> ISEVEN(
     r
 )) * (MOD(
     SQRT(
     n
 ),
      1
 ) = 0) * (MOD(
     SQRT(
     r
 ),
      1
 ) = 0)
 ),
    
 IFERROR(
     HSTACK(
         FILTER(
             s,
              ISEVEN(
                  s
              )
         ),
          FILTER(
              s,
               ISODD(
                  s
              )
          )
     ),
      ""
 )
)
Excel solution 10 for Even-Odd Reversed Squares, proposed by Eric Laforce:
=LET(
 l_RevNum,
     LAMBDA(
         x,
         
          LET(
              t,
              TEXT(
                  x,
                  "0"
              ),
               n,
              LEN(
                  t
              ),
               NUMBERVALUE(
                   TEXTJOIN(
                       "",
                       ,
                       MID(
                           t,
                           SEQUENCE(
                               n,
                               ,
                               n,
                               -1
                           ),
                           1
                       )
                   )
               )
          )
          
     ),
    
 s,
     MAP(
         SEQUENCE(
             3100,
              ,
              10
         ),
          LAMBDA(
              x,
               x ^ 2
          )
     ),
    
 r,
     MAP(
         s,
          l_RevNum
     ),
    
 f,
     TAKE(FILTER(s,
     ISODD(
         s+r
     ) * (MOD(
         SQRT(
             r
         ),
         1
     )=0)),
    50),
    
 IFNA(
     HSTACK(
         FILTER(
             f,
              ISEVEN(
                  f
              )
         ),
         FILTER(
             f,
              ISODD(
                  f
              )
         )
     ),
     ""
 )
)
Excel solution 11 for Even-Odd Reversed Squares, proposed by ferhat CK:
=LET(i,TOCOL(MAP(SEQUENCE(3100)^2,LAMBDA(x,LET(a,--CONCAT(MID(x,SEQUENCE(LEN(x),,LEN(x),-1),1)),b,a^0.5,c,x^0.5,IF(
AND((INT(c)=c)*(INT(b)=b),(ISODD(b)+ISODD(c)*1)=1),x,1/0)))),2),IFERROR(HSTACK(FILTER(i,MOD(i,2)=0),FILTER(i,MOD(i,2)=1)),""))
Excel solution 12 for Even-Odd Reversed Squares, proposed by Meganathan Elumalai:
=LET(n,
    SEQUENCE(
        3100,
        ,
        4
    )^2,
    mx,
    MAX(
        LEN(
            n
        )
    ),
    f,
    BYROW(
        MID(
            n,
            SEQUENCE(
                ,
                mx,
                mx,
                -1
            ),
            1
        ),
        CONCAT
    ),
    all,
    TOCOL(n/((MOD(
        f^0.5,
        1
    )=0)*(MOD(
        n,
        2
    )<>MOD(
        f,
        2
    ))),
    3),
    IFNA(
        HSTACK(
            FILTER(
                all,
                ISEVEN(
                    all
                )
            ),
            FILTER(
                all,
                ISODD(
                    all
                )
            )
        ),
        ""
    ))
Excel solution 13 for Even-Odd Reversed Squares, proposed by Erdit Qendro:
=LET(n,
    SEQUENCE(
        9900,
        ,
        10,
        
    ),
    pw,
    n*n,
    
xx,
    MAP(pw,
    LAMBDA(r,
    
LET(sq,
    SEQUENCE(
        ,
        LEN(
            r 
        )
    ),
    
(MOD(
    SQRT(
        CONCAT(
            SORTBY(
                MID(
                    r,
                    sq,
                    1
                ),
                -sq
            )
        )+0
    ),
    1
)=0)
*(ISODD(
    MID(
        r,
        1,
        1
    )+MID(
        r,
        LEN(
             r
        ),
        1
    )
))))),
    
fdata,
    TAKE(
        FILTER(
            pw,
            xx
        ),
        50
    ),
    
resEven,
    FILTER(
        fdata,
        ISEVEN(
            fdata
        )
    ),
    
resOdd,
    FILTER(
        fdata,
        ISODD(
            fdata
        )
    ),
    
VSTACK(
    {"Even",
    "Odd"},
    
    MAP(
        HSTACK(
            resEven,
            resOdd
        ),
        
        LAMBDA(
            a,
            IF(
                ISERROR(
                    a
                ),
                "",
                a
            )
        )
    )
))

Solving the challenge of Even-Odd Reversed Squares with Python

Python solution 1 for Even-Odd Reversed Squares, proposed by Konrad Gryczan, PhD:
import math
import pandas as pd
from pandas import read_excel
path = "678 Perfect Square Even if Reversed.xlsx"
test = read_excel(path,  usecols="A:B", skiprows=1, nrows=39)
def is_square(n):
 root = int(math.isqrt(n))
 return root * root == n
def reverse_digits(n):
 return int(str(n)[::-1])
squares = [i * i for i in range(1, 40000)]
valid = [sq for sq in squares 
 if is_square(reverse_digits(sq)) and (sq % 2 != reverse_digits(sq) % 2)]
result = valid[:50]
max_len = max(len([num for num in result if num % 2 == 0]), len([num for num in result if num % 2 != 0]))
df = pd.DataFrame({
 'Even': [num for num in result if num % 2 == 0] + [None] * (max_len - len([num for num in result if num % 2 == 0])),
 'Odd': [num for num in result if num % 2 != 0] + [None] * (max_len - len([num for num in result if num % 2 != 0]))
})
print(df.equals(test)) # True
                    
                  
Python solution 2 for Even-Odd Reversed Squares, proposed by Alejandro Campos:
import math, time
def is_perfect_square(n):
 return math.isqrt(n) ** 2 == n
def reverse_number(n):
 reversed_num = 0
 while n > 0:
 reversed_num = reversed_num * 10 + n % 10
 n //= 10
 return reversed_num
st_time = time.time()
even_numbers = []
odd_numbers = []
count = 0
n = 4 
while count < 50:
 num = n ** 2
 reversed_num = reverse_number(num)
 if is_perfect_square(reversed_num):
 if (num % 2 == 0 and reversed_num % 2 != 0) or (num % 2 != 0 and reversed_num % 2 == 0):
 if num % 2 == 0:
 even_numbers.append(num)
 else:
 odd_numbers.append(num)
 count += 1
 n += 1
max_length = max(len(even_numbers), len(odd_numbers))
even_numbers.extend([""] * (max_length - len(even_numbers)))
odd_numbers.extend(&[""] * (max_length - len(odd_numbers)))
data = {'Even': even_numbers, 'Odd': odd_numbers}
df = pd.DataFrame(data)
                    
                  
Python solution 3 for Even-Odd Reversed Squares, proposed by Anshu Bantra:
from itertools import count
import math
def is_perfect_square(n: int) -> bool:
 return math.sqrt(n).is_integer()
def even_odd_swappable_sq(total_count: int) -> list[int]:
 result = []
 num = 10
 for _ in count():
 rev_num = int(str(num)[::-1])
 if (num % 2 == 0 and rev_num % 2 != 0) or (num % 2 != 0 and rev_num % 2 == 0):
 if is_perfect_square(num) and is_perfect_square(rev_num):
 result.append(num)
 if len(result) >= total_count:
 break
 
 num += 1
 return result
numbers = even_odd_swappable_sq(50)
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
pd.DataFrame({'Even': pd.Series(even), 'Odd': pd.Series(odd)}).fillna('')
                    
                  

Solving the challenge of Even-Odd Reversed Squares with Python in Excel

Python in Excel solution 1 for Even-Odd Reversed Squares, proposed by Aditya Kumar Darak 🇮🇳:
import itertools
def MyFun(count):
 nums = (
 n
 for n in (i * i for i in itertools.count(10))
 if int(n**0.5) ** 2 == n
 and int(str(n)[::-1]) ** 0.5 % 1 == 0
 and (
 (n % 2 == 0 and int(str(n)[::-1]) % 2 == 1)
 or (n % 2 == 1 and int(str(n)[::-1]) % 2 == 0)
 )
 )
 topN = list(itertools.islice(nums, count))
 evens = [n for n in topN if n % 2 == 0]
 odds = [n for n in topN if n % 2 == 1]
 return pd.DataFrame(
 list(itertools.zip_longest(evens, odds, fillvalue="")), columns=["Even", "Odd"]
 )
result = MyFun(50)
result
                    
                  
Python in Excel solution 2 for Even-Odd Reversed Squares, proposed by Aditya Kumar Darak 🇮🇳:
import itertools
def MyFun(count):
 nums = (
 n
 for n in (i * i for i in itertools.count(10))
 if int(n**0.5) ** 2 == n
 and int(str(n)[::-1]) ** 0.5 % 1 == 0
 and (
 (n % 2 == 0 and int(str(n)[::-1]) % 2 == 1)
 or (n % 2 == 1 and int(str(n)[::-1]) % 2 == 0)
 )
 )
 topN = list(itertools.islice(nums, count))
 evens = [n for n in topN if n % 2 == 0]
 odds = [n for n in topN if n % 2 == 1]
 mx = max(len(evens), len(odds))
 evens.extend([None] * (mx - len(evens)))
 odds.extend([None] * (mx - len(odds)))
 return pd.DataFrame({"Even": evens, "Odd": odds}).fillna("")
result = MyFun(50)
result
                    
                  
Python in Excel solution 3 for Even-Odd Reversed Squares, proposed by Seokho MOON:
def generate_square(count):
 res = [[], []]
 n = 1
 while sum(len(e) for e in res) < count:
 sq = str(n * n)
 if (int(sq[-1]) + int(sq[0])) % 2 == 1:
 if (int(sq[::-1]) ** 0.5).is_integer():
 res[n % 2].append(int(sq))
 n += 1
 df = pd.DataFrame(res).T.fillna("")
 df.columns = ["Even", "Odd"]
 return df
generate_square(50)
                    
                  

Solving the challenge of Even-Odd Reversed Squares with R

R solution 1 for Even-Odd Reversed Squares, proposed by Konrad Gryczan, PhD:
library(tidyverse)
library(readxl)
path = "Excel/678 Perfect Square Even if Reversed.xlsx"
test  = read_excel(path, range = "A2:B40")
is_square = function(n) {
 root = sqrt(n)
 root == floor(root)
}
reverse_digits_vec = function(n) {
 as.integer(sapply(n, function(x) paste0(rev(strsplit(as.character(x), "")[[1]]), collapse = "")))
}
n = 1:40000
squares = n^2
rev_squares = reverse_digits_vec(squares)
valid = is_square(rev_squares) & (squares %% 2 != rev_squares %% 2)
result = squares[valid][1:50] %>% 
 as_tibble() %>%
 mutate(evenodd = ifelse(value %% 2 == 0, "Even", "Odd")) %>%
 mutate(rn = row_number(), .by = evenodd) %>%
 pivot_wider(names_from = evenodd, values_from = value) %>%
 select(-rn)
all.equal(result, test, check.attributes = FALSE)
#> [1] TRUE
                    
                  

&&

Leave a Reply