Skip to content

Instantly share code, notes, and snippets.

@alistaire47
Created February 22, 2018 04:21
Show Gist options
  • Save alistaire47/78568e698bb8c61325cd8301a7d70d3a to your computer and use it in GitHub Desktop.
Save alistaire47/78568e698bb8c61325cd8301a7d70d3a to your computer and use it in GitHub Desktop.
Pythagorean Triples
---
title: "Pythagorean Triples"
author: "Edward Visel"
output:
html_document:
df_print: paged
---
```{r}
library(tidyverse)
legs <- function(P, c){
discriminant <- sqrt(c^2 + 2*P*c - P^2)
a <- (P - c - discriminant) / 2
b <- P - c - a
data.frame(a, b, c, P)
}
triples <- map_df(12:50000, function(P){
c <- seq.int(from = ceiling((sqrt(2) - 1) * P), # 45-45-90
to = floor((P - 1) / 2), # flat
by = 1L)
discriminant <- sqrt(c^2 + 2*P*c - P^2)
a <- (P - c - discriminant) / 2
is_triple <- a %% 1 == 0
if (any(is_triple)) {
a <- a[is_triple]
c <- c[is_triple]
b <- P - c - a
list(P = rep(P, length(a)),
a = a,
b = b,
c = c)
} else NULL
})
```
```{r}
plot_triples <- function(aes, ylab = deparse(aes$y), max_c = 20500){
triples %>%
filter(c < max_c) %>%
mutate(a_parity = ifelse(a %% 2 == 0, 'even', 'odd')) %>%
ggplot(aes) +
geom_point(size = 0.5, alpha = 0.5) +
scale_x_continuous(labels = scales::comma_format(), expand = c(0, 0)) +
scale_y_continuous(labels = scales::comma_format(), expand = c(0, 0)) +
viridis::scale_color_viridis(
begin = 0.3, end = 0.9, option = 'viridis', discrete = TRUE,
guide = guide_legend(override.aes = list(alpha = 1))) +
labs(title = 'Pythagorean Triples',
y = ylab,
color = expression(Parity~of~italic(a))) +
hrbrthemes::theme_ipsum_rc(plot_margin = margin(10, 10, 5, 10),
grid = FALSE) +
theme(legend.position = 'bottom',
legend.direction = 'horizontal',
legend.key.size = unit(10, 'pt'),
legend.justification = 0.01,
legend.margin = margin(0, 0, 0, 0),
legend.title = element_text(size = 10),
axis.title.y = element_text(angle = 0))
}
```
```{r}
plot_triples(aes(c, a/c, color = a_parity), ylab = expression(over(a, c)))
```
```{r}
plot_triples(aes(b, a, color = a_parity))
```
```{r}
plot_triples(aes(c, a, color = a_parity))
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment