Skip to content

Instantly share code, notes, and snippets.

@darokun
Created February 23, 2017 13:20
Show Gist options
  • Save darokun/9196aebdcc7ac1eb35d80539a58a9c15 to your computer and use it in GitHub Desktop.
Save darokun/9196aebdcc7ac1eb35d80539a58a9c15 to your computer and use it in GitHub Desktop.
Finding square numbers that are also triangular numbers
# Finding square numbers that are also triangular numbers
# This snippet of code has been inspired by Matt Parker's book: Things to make and do in the fourth dimension, Chapter 3, pg. 50
# Square numbers
SqNum <- function(to, from = 1) {
x <- NULL
for(i in seq(from = from, to = to)) {
x[i] <- i^2
}
x <- na.omit(x)
attributes(x) <- NULL
return(x)
}
# Triangular numbers
TriNum <- function(to, from = 1) {
x <- NULL
for(i in seq(from = from, to = to)) {
x[i] <- (i*(i+1))/2
}
x <- na.omit(x)
attributes(x) <- NULL
return(x)
}
# Compare and find matches between square and triangular numbers
SqTri <- function(to, from = 1) {
sqn <- NULL
trin <- NULL
sqn <- SqNum(to = to, from = from)
trin <- TriNum(to = to, from = from)
res <- trin[trin %in% sqn]
print(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment