Home » Triangular Pair Sums and Differences

Triangular Pair Sums and Differences

We had some challenges on Triangular numbers. A triangular number is given by the formula n(n+1)/2. Hence, first few Triangular numbers are 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105…. Find the first 20 pairs of triangular numbers whose absolute difference as well as sum of elements of pairs are also Triangular numbers. Ex. 15, 21 = Absolute diff is 6 and sum is 36. 6 and 36 both are Triangular numbers.

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

Solving the challenge of Triangular Pair Sums and Differences with Power Query

Power Query solution 1 for Triangular Pair Sums and Differences, proposed by Alejandro Simón 🇵🇦 🇪🇸:
let
  Source = List.Buffer(List.Transform({2 .. 2000}, each _ * (_ + 1) / 2)), 
  Lista = Table.FromColumns({Source}), 
  Comb = Table.AddColumn(Lista, "A", each Source), 
  Expand = Table.ExpandListColumn(Comb, "A"), 
  Diff = Table.AddColumn(Expand, "B", (x) => x[A] - x[Column1]), 
  AddCol = Table.AddColumn(Diff, "C", each [Column1] + [A]), 
  B = Table.SelectRows(AddCol, each [B] > 2), 
  Sel = Table.SelectRows(B, each List.Contains(Source, [B]) and List.Contains(Source, [C])), 
  Sol = List.FirstN(
    Table.AddColumn(Sel, "Answer", each Text.From([Column1]) & ", " & Text.From([A]))[Answer], 
    20
  )
in
  Sol
Power Query solution 2 for Triangular Pair Sums and Differences, proposed by Mihai Radu O:
let
  l = {1 .. 2000}, 
  f = (x) =>
    let
      a = Number.Sqrt(1 + 8 * x), 
      b = Int64.From(a) = a and x > 0
    in
      b, 
  s = [
    lt = List.Transform, 
    ltm = List.TransformMany, 
    tf = Text.From, 
    nf = Number.From, 
    a = lt(l, (x) => x * (x + 1) * 0.5), 
    b = ltm(a, (x) => a, (x, y) => {tf(x) & ", " & tf(y), x + y, Number.Abs(x - y)}), 
    c = List.RemoveNulls(lt(b, (x) => if f(x{1}) and f(x{2}) then x{0} else null)), 
    d = List.FirstN(
      List.Distinct(
        lt(c, (x) => Text.Combine(lt(List.Sort(lt(Text.Split(x, ", "), nf)), tf), ", "))
      ), 
      20
    )
  ][d]
in
  s
Power Query solution 3 for Triangular Pair Sums and Differences, proposed by Mihai Radu O:
let
  l = {1 .. 2000}, 
  f = (x) =>
    let
      a = Number.Sqrt(1 + 8 * x), 
      b = Int64.From(a) = a and x > 0
    in
      b, 
  s = [
    lt = List.Transform, 
    ltm = List.TransformMany, 
    tf = Text.From, 
    nf = Number.From, 
    a = lt(l, (x) => x * (x + 1) * 0.5), 
    b = List.Distinct(
      ltm(
        a, 
        (x) => a, 
        (x, y) => {Text.Combine(lt(List.Sort({x, y}), tf), ", "), x + y, Number.Abs(x - y)}
      )
    ), 
    c = List.RemoveNulls(lt(b, (x) => if f(x{1}) and f(x{2}) then x{0} else null)), 
    d = List.FirstN(c, 20)
  ][d]
in
  s

Solving the challenge of Triangular Pair Sums and Differences with Excel

Excel solution 1 for Triangular Pair Sums and Differences, proposed by Bo Rydobon 🇹🇭:
=TOCOL(MAP(SEQUENCE(
    1400
),
    LAMBDA(n,
    LET(t,
    n*(n+1),
    s,
    SEQUENCE(
        n-1
    ),
    u,
    s*(s+1),
    m,
    t+{1,
    -1}*u,
    o,
    ROUND(
        m^0.5,
        
    ),
    FILTER(u/2,
    BYROW(o*(o+1)=m,
    AND))&", "&t/2))),
    3)
Excel solution 2 for Triangular Pair Sums and Differences, proposed by Bo Rydobon 🇹🇭:
=LET(n,
    SEQUENCE(
        1362
    ),
    t,
    n*(n+1)/2,
    r,
    TOROW(
        t
    ),
    TOCOL(
        IF(
            r
Excel solution 3 for Triangular Pair Sums and Differences, proposed by John V.:
=LET(s,
    SCAN(
        ,
        SEQUENCE(
            1750
        ),
        SUM
    ),
    t,
    TOROW(
        s
    ),
    f,
    LAMBDA(
        n,
        MOD(
            SQRT(
                1+8*n
            ),
            2
        )=1
    ),
    TAKE(TOCOL(IFS((s
Excel solution 4 for Triangular Pair Sums and Differences, proposed by Julian Poeltl:
=LET(N,
    SEQUENCE(
        2000
    ),
    T,
    N*(N+1)/2,
    R,
    TAKE(
        TOCOL(
            UNIQUE(
                MAP(
                    T,
                    LAMBDA(
                        A,
                        LET(
                            X,
                            XLOOKUP(
                                1,
                                ISNUMBER(
                                    XMATCH(
                                        ABS(
                                            T-A
                                        ),
                                        T
                                    )
                                )*ISNUMBER(
                                    XMATCH(
                                        T+A,
                                        T
                                    )
                                ),
                                T
                            ),
                            IF(
                                A>X,
                                X&", "&A,
                                A&", "&X
                            )
                        )
                    )
                )
            ),
            3
        ),
        20
    ),
    SORTBY(
        R,
        --TEXTBEFORE(
            R,
            ","
        )
    ))
Excel solution 5 for Triangular Pair Sums and Differences, proposed by Timothée BLIOT:
=LET(A,
    SEQUENCE(
        1800
    ),
    B,
    A*(A+1)/2,
    C,
    MAP(
        B-TOROW(
            B
        ),
        B+TOROW(
            B
        ),
        LAMBDA(
            x,
            y,
            IF(
                x>0,
                ISNUMBER(
                    XMATCH(
                        x,
                        B
                    )
                )*ISNUMBER(
                    XMATCH(
                        y,
                        B
                    )
                ),
                0
            )
        )
    ),
    F,
    LAMBDA(
        n,
        TOCOL(
            IF(
                C,
                n,
                1/0
            ),
            3
        )
    ),
    
BYROW(
    SORT(
        HSTACK(
            F(
                TOROW(
            B
        )
            ),
            F(
            B
        )
        )
    ),
    LAMBDA(
        x,
        ARRAYTOTEXT(
            x
        )
    )
))
Excel solution 6 for Triangular Pair Sums and Differences, proposed by Oscar Mendez Roca Farell:
=LET(n,
     2000,
     s,
     SEQUENCE(
         n
     )+1,
     m,
    s*(s-1)/2,
     t,
     TOROW(
         m
     ),
     F,
     LAMBDA(
         i,
          XLOOKUP(
              i,
               m,
               m,
               0
          )
     ),
     TOCOL(IFS(F(
         ABS(
             m-t
         )
     )/F(
         m+t
     )/(t>m),
     m&", "&t),
     2))
Excel solution 7 for Triangular Pair Sums and Differences, proposed by Sunny Baggu:
=LET(
 n, SEQUENCE(2000),
 _a, n * (n + 1) / 2,
 _b, TOROW(_a),
 _c, TOCOL(
 IF(
 XMATCH(ABS(_a - _b), _a) + XMATCH(ABS(_a + _b), _a),
 _a & "," & _b
 ),
 3
 ),
 TAKE(
 UNIQUE(
 MAP(_c, LAMBDA(a, ARRAYTOTEXT(SORT(TEXTSPLIT(a, , ",") + 0))))
 ),
 20
 )
)
Excel solution 8 for Triangular Pair Sums and Differences, proposed by LEONARD OCHEA 🇷🇴:
=LET(U,TEXTJOIN,S,SEQUENCE,TEXTSPLIT(U("|",,TOCOL(MAP(S(900),LAMBDA(y,LET(x,S(,9*y,y+1),a,(x^2+x)/2,b,(y^2+y)/2,c,(8*(a+{-1;1}*b)+1)^0.5,U("|",,IFERROR(TOROW(IF(BYCOL(IFERROR(--(MOD(c,1)=0),),SUM)=2,b&", "&a,z),3),z))))),3)),,"|"))
Excel solution 9 for Triangular Pair Sums and Differences, proposed by Bilal Mahmoud kh.:
=r)),
    res,
    MAP(n_1,
    LAMBDA(x,
    TEXTJOIN("-",
    TRUE,
    MAP(DROP(
        n_1,
        MATCH(
            x,
            n_1,
            0
        )-1
    ),
    LAMBDA(y,
    IF((x<>y)*tran(
        y-x
    )*tran(
        y+x
    ),
    x&"-"&y,
    "")))))),
    FILTER(
        res,
        res<>""
    ))

Solving the challenge of Triangular Pair Sums and Differences with Python

Python solution 1 for Triangular Pair Sums and Differences, proposed by Konrad Gryczan, PhD:
Some numbers are not matching. I'll check it later.
import pandas as pd
path = "547 Sum and Diff both Triangular Numbers.xlsx"
test = pd.read_excel(path, usecols="A")
def generate_triangular_numbers(limit):
 return [n * (n + 1) // 2 for n in range(1, int((2 * limit) ** 0.5) + 1)]
def is_triangular_number(n):
 return ((8 * n + 1) ** 0.5).is_integer()
triangulars = generate_triangular_numbers(1000000)
triangulars_df = pd.DataFrame({'t1': triangulars})
result = triangulars_df.assign(key=0).merge(triangulars_df.assign(key=0), on='key').drop(columns='key')
result.columns = ['t1', 't2']
result = result[(result['t1'] < result['t2']) & 
 (result['t1'] + result['t2']).apply(is_triangular_number) & 
 (abs(result['t2'] - result['t1'])).apply(is_triangular_number) & 
 (result['t1'] != result['t2'])].reset_index(drop=True)
print(result)
                    
                  
Python solution 2 for Triangular Pair Sums and Differences, proposed by Konrad Gryczan, PhD:
import pandas as pd
import numpy as np
path = "547 Sum and Diff both Triangular Numbers.xlsx"
test = pd.read_excel(path, usecols="A")
def generate_triangular_numbers(n):
 return [i * (i + 1) // 2 for i in range(1, n + 1)]
def is_triangular_number(n):
 return ((8 * n + 1) ** 0.5).is_integer()
triangulars = generate_triangular_numbers(2000)
triangulars_df = pd.DataFrame({'t1': triangulars})
result = triangulars_df.assign(key=0).merge(triangulars_df.assign(key=0), on='key').drop(columns='key')
result.columns = ['t1', 't2']
result = result[(result['t1'] < result['t2']) & 
 (result['t1'] + result['t2']).apply(is_triangular_number) & 
 (abs(result['t2'] - result['t1'])).apply(is_triangular_number) & 
 (result['t1'] != result['t2'])].reset_index(drop=True)
result['output'] = result['t1'].astype(str) + ', ' + result['t2'].astype(str)
result = result.head(20)
print(result['output'].equals(test["Answer Expected"]))
                    
                  
Python solution 3 for Triangular Pair Sums and Differences, proposed by Abdallah Ally:
let
 Source = Python.Execute("from itertools import combinations #(lf)import pandas as pd#(lf)#(lf)# Create a function to categorize numbers as either triangulars or not#(lf)def is_triang(num):#(lf)  s = ((8 * num + 1) ** 0.5 - 1)/2#(lf)  return s == int(s)#(lf)  #(lf)# Perform data manipulation  #(lf)triangulars = map(lambda n: n * (n + 1)//2, range(1, 2000))#(lf)pairs = filter(#(lf)  lambda n: is_triang(sum(n)) and is_triang(abs(n[0]-n[1])), #(lf)  combinations(triangulars, 2)#(lf))#(lf)pairs = sorted(set(map(lambda n: tuple(sorted(n)), pairs)))[:20]#(lf)pairs = [', '.join(map(str, n)) for n in pairs]#(lf)#(lf)data = pd.DataFrame(data={'TriangularPairs': pairs})"),
 Result = Source{[Name="data"]}[Value]
in
 Result
                    
                  

Solving the challenge of Triangular Pair Sums and Differences with Python in Excel

Python in Excel solution 1 for Triangular Pair Sums and Differences, proposed by Alejandro Campos:
import math
def triangular_number(n):
 return n * (n + 1) // 2
def is_triangular(x):
 discriminant = 1 + 8 * x
 sqrt_discriminant = math.isqrt(discriminant)
 return discriminant == sqrt_discriminant ** 2 and (-1 + sqrt_discriminant) % 2 == 0
def generate_triangular_numbers(n):
 return [triangular_number(i) for i in range(1, n + 1)]
def find_triangular_pairs(limit):
 triangular_numbers = generate_triangular_numbers(2000)
 valid_pairs = []
 for i in range(len(triangular_numbers)):
 for j in range(i + 1, len(triangular_numbers)):
 t1 = triangular_numbers[i]
 t2 = triangular_numbers[j]
 diff = abs(t1 - t2)
 total_sum = t1 + t2
 if is_triangular(diff) and is_triangular(total_sum):
 valid_pairs.append(f'{t1}, {t2}')
 if len(valid_pairs) >= limit:
 return valid_pairs
 
 return valid_pairs
pairs = find_triangular_pairs(20)
result = pd.DataFrame(pairs, columns=['Triangula Pairs'])
result
                    
                  
Python in Excel solution 2 for Triangular Pair Sums and Differences, proposed by Abdallah Ally:
from itertools import combinations
# Create a function to categorize numbers 
# as either triangulars or not
def is_triang(num):
 s = ((8 * num + 1) ** 0.5 - 1)/2
 return s == int(s)
# Perform data manipulation 
triangulars = map(lambda n: n * (n + 1)//2, range(1, 2000))
pairs = filter(
 lambda n: is_triang(sum(n)) and is_triang(abs(n[0]-n[1])), 
 combinations(triangulars, 2)
)
pairs = sorted(set(map(lambda n: tuple(sorted(n)), pairs)))[:20]
pairs = [', '.join(map(str, n)) for n in pairs]
pairs
                    
                  

Solving the challenge of Triangular Pair Sums and Differences with R

R solution 1 for Triangular Pair Sums and Differences, proposed by Konrad Gryczan, PhD:
library(tidyverse)
library(readxl)
path = "Excel/547 Sum and Diff both Triangular Numbers.xlsx"
test = read_excel(path, range = "A1:A21")
generate_triangular_numbers <- function(limit) {
 n <- 1
 triangulars <- c()
 
 while (TRUE) {
 t_n <- n * (n + 1) / 2
 if (t_n > limit) break
 triangulars <- c(triangulars, t_n)
 n <- n + 1
 }
 return(triangulars)
}
is_triangular_number <- function(n) {
 return((sqrt(8 * n + 1) - 1) %% 2 == 0)
}
tr = generate_triangular_numbers(1000000)
tr_pairs = expand.grid(tr, tr) %>%
 as_tibble() %>%
 filter(Var1 != Var2,
 Var1 < Var2,
 is_triangular_number(Var1 + Var2),
 is_triangular_number(abs(Var1 - Var2))) %>%
 arrange(Var1, Var2) %>%
 head(20) %>%
 unite("result", c(Var1, Var2), sep = ", ", remove = T)
print(tr_pairs)
                    
                  
R solution 2 for Triangular Pair Sums and Differences, proposed by Konrad Gryczan, PhD: &
library(tidyverse)
library(readxl)
path = "Excel/547 Sum and Diff both Triangular Numbers.xlsx"
test = read_excel(path, range = "A1:A21")
generate_triangular_numbers <- function(n) {
 triangulars <- numeric(n)
 for (i in 1:n) {
 triangulars[i] <- i * (i + 1) / 2 
 }
 return(triangulars)
}
is_triangular_number <- function(n) {
 return((sqrt(8 * n + 1) - 1) %% 2 == 0)
}
tr = generate_triangular_numbers(2000)
tr_pairs = expand.grid(tr, tr) %>%
 as_tibble() %>%
 filter(Var1 != Var2,
 Var1 < Var2,
 is_triangular_number(Var1 + Var2),
 is_triangular_number(abs(Var1 - Var2))) %>%
 arrange(Var1, Var2) %>%
 head(20) %>%
 unite("result", c(Var1, Var2), sep = ", ", remove = T)
identical(test$`Answer Expected`, tr_pairs$result)
#> [1] TRUE
                    
                  

&&

Leave a Reply