Created
February 23, 2017 13:20
-
-
Save darokun/9196aebdcc7ac1eb35d80539a58a9c15 to your computer and use it in GitHub Desktop.
Finding square numbers that are also triangular numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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