{"id":235,"date":"2024-04-30T11:04:31","date_gmt":"2024-04-30T10:04:31","guid":{"rendered":"https:\/\/dharma-code.com\/wordpress\/?p=235"},"modified":"2024-05-02T03:40:05","modified_gmt":"2024-05-02T02:40:05","slug":"calculating-pythagorean-triples-and-rational-numbers-from-fibonacci-sequence-java","status":"publish","type":"post","link":"https:\/\/dharma-code.com\/wordpress\/index.php\/2024\/04\/30\/calculating-pythagorean-triples-and-rational-numbers-from-fibonacci-sequence-java\/","title":{"rendered":"Calculating Pythagorean Triples and Rational Numbers from the Fibonacci Sequence in Java"},"content":{"rendered":"\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50 has-custom-font-size is-style-outline mb-3 has-medium-font-size is-style-outline--1\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/github.com\/dharma-code-chris\/pythagonacci\" style=\"border-radius:6px\" target=\"_blank\" rel=\"noreferrer noopener\">View on GitHub<\/a><\/div>\n<\/div>\n\n\n\n<p>A while back I came across a <a href=\"https:\/\/www.youtube.com\/watch?v=94mV7Fmbx88\" target=\"_blank\" rel=\"noopener\" title=\"\">fascinating video on YouTube<\/a> by <a href=\"https:\/\/www.youtube.com\/@Mathologer\" target=\"_blank\" rel=\"noopener\" title=\"\">Mathologer<\/a>, which described a little-known pair of discoveries that were made in <a href=\"https:\/\/arxiv.org\/abs\/math\/0701554\" target=\"_blank\" rel=\"noopener\" title=\"\">2007<\/a> and <a href=\"https:\/\/arxiv.org\/abs\/0809.4324\" target=\"_blank\" rel=\"noopener\" title=\"\">2008<\/a> relating to a connection between the Fibonacci sequence and the Pythagorean triples. I have embedded the video at the end of this article, where you can learn all about the discovery.<\/p>\n\n\n\n<p>In this article I would like to give an overview of this relationship between the Pythagorean triples and the Fibonacci sequence. We will then implement an algorithm in Java 17 using Maven that will perform the calculation upon which the relationship is based, calling it the <em>Pythagonacci<\/em> <em>Box Tree<\/em> (what H. Lee Price in his <a href=\"https:\/\/arxiv.org\/abs\/0809.4324\" target=\"_blank\" rel=\"noopener\" title=\"\">2008 article<\/a> refers to as the &#8220;New Pythagorean Tree&#8221;.)<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Fibonacci Sequence<\/h2>\n\n\n\n<p>The Fibonacci Sequence is a series of numbers where each number is the sum of the two preceding ones. Mathematically, it is defined by the recurrence relation:<\/p>\n\n\n\n<p><em>F(n) = F(n &#8211; 1) + F(n &#8211; 2)<\/em><\/p>\n\n\n\n<p>Commonly it is represented with the following seed values:<\/p>\n\n\n\n<p><em>F(0)=0, F(1)=1<\/em><\/p>\n\n\n\n<p>However, for the purposes of this article we are going to offset the zero and begin with 1, 1.<\/p>\n\n\n\n<p>The first four numbers in our Fibonacci sequence are therefore 1, 1, 2, 3.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pythagorean Triples<\/h2>\n\n\n\n<p>Pythagorean Triples are sets of three positive integers <em>a<\/em>, <em>b<\/em>, and <em>c<\/em>, such that:<\/p>\n\n\n\n<p> <em>a<\/em><code><sup>2<\/sup><\/code><em> + b<\/em><code><sup>2<\/sup><\/code><em> = c<\/em><code><sup>2<\/sup><\/code><\/p>\n\n\n\n<p>These number sets form the sides of right-angled triangles, with <em>c<\/em> being the hypotenuse.<\/p>\n\n\n\n<p>The first Pythagorean triple has values a = 3, b = 4 and c = 5, since:<\/p>\n\n\n\n<p><code>3<code><sup>2<\/sup><\/code> + 4<code><sup>2<\/sup><\/code> = 5<sup>2<\/sup><\/code><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Relationship Between the Fibonacci Sequence and Pythagorean Triples<\/h2>\n\n\n\n<p>Starting with the set of the first four numbers in the Fibonacci sequence, <code>{ 1, 1, 2, 3 }<\/code>, we curve them clockwise into a 2 x 2 matrix, we shall call this a <em>box, <\/em>as follows:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"has-cyan-bluish-gray-background-color has-background\"><tbody><tr><td> <strong>1<\/strong> <\/td><td> <strong>1<\/strong> <\/td><\/tr><tr><td> <strong>3<\/strong> <\/td><td> <strong>2<\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><em>Pythagonacci <\/em>root box (0) values<\/figcaption><\/figure>\n\n\n\n<p>The structure of a box can therefore be defined as follows (we will call this the <em><strong>box definition<\/strong>)<\/em>:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"has-vivid-cyan-blue-background-color has-background\"><tbody><tr><td><strong><em>V-U<\/em><\/strong><\/td><td> <strong><em>U<\/em><\/strong> <\/td><\/tr><tr><td><strong><em>V+U<\/em><\/strong><\/td><td> <strong><em>V<\/em><\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><em>Pythagonacci<\/em> box definition<\/figcaption><\/figure>\n\n\n\n<p>We then denote each of these values as a separate variable as follows:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"has-pale-pink-background-color has-background\"><tbody><tr><td> <strong><em>a<\/em><\/strong> <\/td><td> <strong><em>b<\/em><\/strong> <\/td><\/tr><tr><td> <strong><em>d<\/em><\/strong> <\/td><td> <strong><em>c<\/em><\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><em>Pythagonacci <\/em>box variables<\/figcaption><\/figure>\n\n\n\n<p>We can then apply three functions to these variables to produce the first Pythagorean triple:<\/p>\n\n\n\n<p><code><em>F1 <\/em>+ <em>F2 <\/em>= <em>F3<\/em><\/code><\/p>\n\n\n\n<p><code><em>F1 <\/em>= (<em>a<\/em> x <em>d<\/em>)<sup>2<\/sup><\/code><\/p>\n\n\n\n<p><code><em>F2<\/em> = (2<em> <\/em>x<em> b<\/em> x <em>c<\/em>)<sup>2<\/sup><\/code><\/p>\n\n\n\n<p><code><em>F3 <\/em>= (<em>a<\/em><code><em> <\/em>x<em> <\/em><\/code><em>c <\/em>+ <em>b<\/em><code><em> <\/em>x<em> <\/em><\/code><em>d<\/em>)<sup>2<\/sup><\/code><\/p>\n\n\n\n<p><code>(1<code><em> <\/em>x<em> <\/em><\/code>3)<sup>2<\/sup> + (2<code><em> <\/em>x<\/code> (1<code><em> <\/em>x<em> <\/em><\/code>2))<code><sup>2<\/sup><\/code> = ((1<code><em> <\/em>x<em> <\/em><\/code>2)+(1<code><em> <\/em>x<em> <\/em><\/code>3))<code><sup>2<\/sup><\/code><\/code><\/p>\n\n\n\n<p><code>3<code><sup>2<\/sup><\/code> + 4<code><sup>2<\/sup><\/code> = 5<sup>2<\/sup><\/code><\/p>\n\n\n\n<p>In the YouTube video (see below) you may notice that the order of variables <em>a<\/em>, <em>b<\/em>, <em>c<\/em> and <em>d<\/em> is slightly different. I have chosen to use a clockwise arrangement because it maps to the Fibonacci sequence.<\/p>\n\n\n\n<p>We then construct three empty boxes and apply three different transformations to the original box to produce the seed blueprints for three <strong><em>child<\/em> <\/strong>boxes: <em><strong>X<\/strong><\/em>, <strong><em>Y<\/em> <\/strong>and <em><strong>Z<\/strong><\/em>, the original being the <em><strong>parent<\/strong><\/em>. Each of the three transformations begins by selecting two values from the parent and locating them in the children as indicated by the positions of the variables shown here:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>b<\/em><\/strong> <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>d<\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint: Child box <em>X<\/em><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table aligncenter table-2\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>c<\/em><\/strong><\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint: Child box <em>Y<\/em><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table aligncenter table-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>a<\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>c<\/em><\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint: Child box <em>Z<\/em><\/figcaption><\/figure>\n\n\n\n<p>It will help with the layout in the article if we visualise these three child boxes joined side-by-side. I have also added some colour to make it clearer what happens in the subsequent step.<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1-2-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>b <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>a <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">d<\/mark> <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">d<\/mark> <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">c<\/mark> <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">c<\/mark> <\/em><\/strong><\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint step 1: Child boxes <em>X<\/em>, <em>Y<\/em> and <em>Z<\/em><\/figcaption><\/figure>\n\n\n\n<p>The next step involves a transform on each of the child boxes where the values from the bottom row are moved up into the empty cells in the top row, as follows:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1-2-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong> <em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">d<\/mark><\/em> <\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>b <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">d<\/mark><\/em> <\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">c<\/mark><\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>a <\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">c<\/mark><\/em> <\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><td class=\"has-text-align-center\" data-align=\"center\"> &#8211; <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint step 2: Child boxes <em>X<\/em>, <em>Y<\/em> and <em>Z<\/em> shifted up<\/figcaption><\/figure>\n\n\n\n<p>By reference to the <em><strong>box definition<\/strong><\/em> from above, we can then populate the empty cells in the bottom row thus:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1-2-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong><em>d<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>b<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>c<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>a<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>c<\/em><\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d+b+b<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d+b<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d+c+c<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>d+c<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>a+c+c<\/em><\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em>a+c<\/em><\/strong><\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Seed blueprint step 3: Child boxes <em>X<\/em>, <em>Y<\/em> and <em>Z<\/em> population via <em>box definition<\/em><\/figcaption><\/figure>\n\n\n\n<p>Substituting the values for <em>a<\/em>, <em>b<\/em>, <em>c<\/em> and <em>d<\/em> from the parent box, we get the following:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1-2-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong>3<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>1<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>3<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><em> <\/em><strong>2<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>1<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>2<\/strong> <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"> <strong>5<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>4<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>7<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>5<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>5<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"> <strong>3<\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Child boxes <em>X<\/em>, <em>Y<\/em> and <em>Z<\/em><\/figcaption><\/figure>\n\n\n\n<p>Next, we assign the values in each of the child boxes to their own equivalent <strong><em>a<\/em><\/strong>, <strong><em>b<\/em><\/strong>, <strong><em>c<\/em><\/strong>, and <strong><em>d<\/em><\/strong>:<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter table-1-2-3\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> a<sup>x<\/sup><\/strong> <\/em><\/td><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> b<sup>x<\/sup> <\/strong><\/em><\/td><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> a<sup>y<\/sup><\/strong><\/em> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> b<sup>y<\/sup> <\/strong><\/em><\/td><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> a<sup>z<\/sup><\/strong><\/em> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><em><strong> b<sup>z<\/sup> <\/strong><\/em><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> d<sup>x<\/sup><\/em> <\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> c<sup>x<\/sup><\/em> <\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> d<sup>y<\/sup><\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> c<sup>y<\/sup><\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> d<sup>z<\/sup><\/em><\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong><em> c<sup>z<\/sup><\/em><\/strong> <\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Child boxes <em>X<\/em>, <em>Y<\/em> and <em>Z<\/em><\/figcaption><\/figure>\n\n\n\n<p>Finally, for each of the child boxes, when we apply the functions <strong><em>F1<\/em><\/strong>, <strong><em>F2 <\/em><\/strong>and <strong><em>F3 <\/em><\/strong>discussed above to the variables <strong><em>a<\/em><\/strong>, <strong><em>b<\/em><\/strong>, <strong><em>c <\/em><\/strong>and <strong><em>d<\/em><\/strong>, we <strong><em>ALWAYS <\/em><\/strong>get Pythagorean triples!<\/p>\n\n\n\n<p><code>(<em>a<\/em> x <em>d<\/em>)<sup>2<\/sup> + (2<code><em> <\/em>x<em> <\/em><\/code><em>b<\/em><code><em> <\/em>x<em> <\/em><\/code><em>c<\/em>)<sup>2<\/sup> = (<em>a<\/em><code><em> <\/em>x<em> <\/em><\/code><em>c <\/em>+ <em>b<\/em><code><em> <\/em>x<em> <\/em><\/code><em>d<\/em>)<sup>2<\/sup><\/code><\/p>\n\n\n\n<p><code>X: (3<em> <\/em>x<em> <\/em>5)<sup>2<\/sup> + (2<em> <\/em>x<em> <\/em>1<em> <\/em>x<em> <\/em>4)<sup>2<\/sup> = (3<em> <\/em>x<em> <\/em>4 + 1<em> <\/em>x<em> <\/em>5)<sup>2<\/sup> =&gt; <strong>15<sup>2<\/sup> + 8<sup>2<\/sup> = 17<sup>2<\/sup><\/strong><\/code><\/p>\n\n\n\n<p><code>Y: (3 x 7)<sup>2<\/sup> + (2 x 2 x 5)<sup>2<\/sup> = (3 x 5 + 2 x 7)<sup>2<\/sup> =&gt; <strong>21<sup>2<\/sup> + 20<sup>2<\/sup> = 29<sup>2<\/sup><\/strong><\/code><\/p>\n\n\n\n<p><code>Z: (1 x 5)<sup>2<\/sup> + (2 x 2 x 3)<sup>2<\/sup> = (1 x 3 + 2 x 5)<sup>2<\/sup> =&gt; <strong>5<sup>2<\/sup> + 12<sup>2<\/sup> = 13<sup>2<\/sup><\/strong><\/code><\/p>\n\n\n\n<p>Each child box can then be transformed respectively to generate three children of its own, and each child will always produce a NEW Pythagorean triple. <strong>Continuing indefinitely in this way constructs a <em>Pythagonacci Box Tree<\/em>, in which every single <em>primitive <\/em>Pythagorean triple will be produced EXACTLY ONCE.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Relationship Between the Fibonacci Sequence and the Rational Numbers<\/h2>\n\n\n\n<p>As if that were not enough, there is another interesting outcome of the above algorithm that identifies a fundamental relationship between the Fibonacci sequence and the rational numbers.<\/p>\n\n\n\n<p>If we consider each column of the boxes in turn and take the top row value as numerator and the bottom row values as denominator, then we arrive at rational numbers in the form <em>a<\/em>\/<em>d<\/em> and <em>b<\/em>\/<em>c<\/em>. It has been proven that if we apply this process to every box indefinitely, <strong>we will get every single rational number between zero and one EXACTLY ONCE!<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Java Implementation<\/h2>\n\n\n\n<p>I thought that these results were incredible &#8211; that this one algorithm could produce all of the Pythagorean triples AND all of the rational numbers between zero and one, and that it all arises from the simplicity of the Fibonacci sequence. It led me to want to write an implementation of the algorithm in Java, and this is where we shall now turn.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Class: PythagonacciBox<\/h2>\n\n\n\n<p>The main class in our Java implementation is going to be called <code>PythagonacciBox<\/code>. It will need to contain the four values for the box itself. Since we will be using recursion to generate each subsequent row of child boxes, to avoid stack overflows we will also need to give it an <code>altitude<\/code> that decreases with each subsequent generation and stops recursing when it gets below zero. We will also give it an <code>id<\/code> that will help us to locate the box in the overall structure when we come to log its values.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public class PythagonacciBox {\n\t\n    private final Integer altitude;\n\t\n    private final Long&#91;] values;\n\t\n    private final String id;\n\t\n    \/**\n     * Constructor for root box.\n     *\/\n    public PythagonacciBox(Integer altitude, Long&#91;] values) {\n        this(altitude, values, null, \"0\");\n    }\n\n    public PythagonacciBox(Integer altitude, Long&#91;] values,\n            PythagonacciBox parent, String relativeId) {\n        \/\/ Descend towards the bottom of the tree by one step:\n        this.altitude = altitude - 1;\n        if (values.length != 4) {\n            throw new IllegalArgumentException(\"values must be length 4\");\n        }\n        this.values = values;\n        this.id = parent != null ? parent.getId() + relativeId : relativeId;\n    }\n\n    public String getId() {\n        return id;\n    }\n}<\/code><\/pre>\n\n\n\n<p>I&#8217;ve included a sanity check to ensure the values are the correct length. Notice that we have two constructors: One for the &#8220;root&#8221; box, and another for general use. The root box doesn&#8217;t have a parent, so it is a special case.<\/p>\n\n\n\n<p>The <code>id<\/code> is going to represent a box&#8217;s address in the box tree. The root box will have an id of &#8220;0&#8221;. Child boxes will be denoted using X, Y or Z, appended to the parent box&#8217;s id. For example, if a box has an id of &#8220;0XYYXZ&#8221; it means that the box is located by going from the root box &#8220;0&#8221; to its child &#8220;0X&#8221;, to its child &#8220;0XY&#8221;, to its child &#8220;0XYY&#8221;, to its child &#8220;0XYYX&#8221; and finally to its child &#8220;0XYYXZ&#8221;.<\/p>\n\n\n\n<p>We will use constants to represent the indices of the variable positions <em>a<\/em>, <em>b<\/em>, <em>c <\/em>and <em>d<\/em> within the array of values:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>    private static final int IX_A = 0;\n    private static final int IX_B = 1;\n    private static final int IX_C = 2;\n    private static final int IX_D = 3;<\/code><\/pre>\n\n\n\n<p>We will then need three methods: one for the square-root of each of the functions <em>F1<\/em>, <em>F2 <\/em>and <em>F3<\/em>, so that we can print the Pythagorean triples in the format <em>A<\/em><sup>2<\/sup> + <em>B<\/em><sup>2<\/sup> = <em>C<\/em><sup>2<\/sup>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>    public long getPythagoreanTripleSideA() {\n        return values&#91;IX_A] * values&#91;IX_D];\n    }\n\n    public long getPythagoreanTripleSideB() {\n        return 2 * values&#91;IX_B] * values&#91;IX_C];\n    }\n\n    public long getPythagoreanTripleHypotenuse() {\n        return values&#91;IX_A] * values&#91;IX_C] + values&#91;IX_B] * values&#91;IX_D];\n    }<\/code><\/pre>\n\n\n\n<p>Then we need to add a function that will print the Pythagorean triples, and another that will check that the box actually represents a Pythagorean triple. If it doesn&#8217;t, we will have it throw an exception.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>    public String getPythagoreanTripleString() {\n        return String.format(\"%d^2 + %d^2 ?= %d^2\",\n                getPythagoreanTripleSideA(),\n                getPythagoreanTripleSideB(),\n                getPythagoreanTripleHypotenuse());\n    }\n\t\n    public boolean validateIsPythagoreanTriple() {\n        long a = getPythagoreanTripleSideA();\n        long b = getPythagoreanTripleSideB();\n        long c = getPythagoreanTripleHypotenuse();\n        boolean isValid = a * a + b * b == c * c;\n        if (!isValid) {\n            throw new IllegalStateException(id + \" is invalid!\\n\" + this);\n        }\n        return true;\n    }<\/code><\/pre>\n\n\n\n<p>To perform the initialisation of the boxes with the Fibonacci sequence from the first two values, we will include the following static function:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>    private static Long&#91;] fibonacci2x2(long a, long b) {\n        long c = a + b;\n        Long&#91;] newValues = new Long&#91;4];\n        newValues&#91;IX_A] = a;\n        newValues&#91;IX_B] = b;\n        newValues&#91;IX_C] = c;\n        newValues&#91;IX_D] = c + b;\n        return newValues;\n    }<\/code><\/pre>\n\n\n\n<p>We will override <code>toString()<\/code> to print the id, the Pythagorean triple and the values for the box:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>    @Override\n    public String toString() {\n        return String.format(\"%s: %s\\n%d\\t%d\\n%d\\t%d\",\n                id, getPythagoreanTripleString(),\n                values&#91;IX_A], values&#91;IX_B],\n                values&#91;IX_D], values&#91;IX_C]);\n    }<\/code><\/pre>\n\n\n\n<h2 class=\"mt-3 wp-block-heading\">Record: PythagonacciBoxTriplet<\/h2>\n\n\n\n<p>To represent the child boxes of a <code>PythagonacciBox<\/code> we will be using a wrapper that combines three <code><code>PythagonacciBox<\/code><\/code> objects into one. For this we will create a new <code>record<\/code> (a Java 14+ feature) called <strong><code>PythagonacciBoxTriplet<\/code> <\/strong>(Note: we will be adding <code><code>PythagonacciBox<\/code>.toStringRecursive()<\/code> and <code><code>PythagonacciBox<\/code>.validateIsPythagoreanTripleRecursive()<\/code> later, so ignore any compilation errors for now):<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public record PythagonacciBoxTriplet(PythagonacciBox x,\n        PythagonacciBox y, PythagonacciBox z) {\n\n    @Override\n    public String toString() {\n        return x.toString() + y.toString() + z.toString();\n    }\n\n    public String toStringRecursive() {\n        return x.toStringRecursive() +\n                y.toStringRecursive() +\n                z.toStringRecursive();\n    }\n\n    public boolean validateIsPythagoreanTripleRecursive() {\n        return x.validateIsPythagoreanTripleRecursive() &amp;&amp;\n                y.validateIsPythagoreanTripleRecursive() &amp;&amp;\n                z.validateIsPythagoreanTripleRecursive();\n    }\n}<\/code><\/pre>\n\n\n\n<p>Now, returning to our <code>PythagonacciBox<\/code> class, we can add a reference to the children. We will also add the code that will create the children, which we will implement using a lazy-loading pattern within the getter:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public class PythagonacciBox {\n\n    \/\/ ...\n\n    private PythagonacciBoxTriplet children;\n\n    \/\/ ...\n\n    public PythagonacciBoxTriplet getChildren() {\n        if (children == null) {\n            \/\/ Calculate children:\n            \/\/ X: Take values b and d, move d to the top row,\n            \/\/ then Fibonacci clockwise.\n            \/\/ .  b -&gt; d  b -&gt; d     b\n            \/\/ d  . -&gt; .  . -&gt; d+b+b d+b\n            PythagonacciBox x = new PythagonacciBox(altitude,\n                    fibonacci2x2(values&#91;IX_D], values&#91;IX_B]), this, \"X\");\n\n            \/\/ Y: Take values d and c, move them to the top row,\n            \/\/ then Fibonacci clockwise.\n            \/\/ .  . -&gt; d  c -&gt; d     c\n            \/\/ d  c -&gt; .  . -&gt; d+c+c d+c\n            PythagonacciBox y = new PythagonacciBox(altitude,\n                    fibonacci2x2(values&#91;IX_D], values&#91;IX_C]), this, \"Y\");\n\n            \/\/ Z: Take values a and c, move c to the top row,\n            \/\/ then Fibonacci clockwise.\n            \/\/ a  . -&gt; a  c -&gt; a     c\n            \/\/ .  c -&gt; .  . -&gt; a+c+c a+c\n            PythagonacciBox z = new PythagonacciBox(altitude,\n                    fibonacci2x2(values&#91;IX_A], values&#91;IX_C]), this, \"Z\");\n\n            this.children = new PythagonacciBoxTriplet(x, y, z);\n        }\n        return children;\n    }<\/code><\/pre>\n\n\n\n<p>Finally, we will add <code>PythagonacciBox.toStringRecursive()<\/code> and <code>PythagonacciBox.validateIsPythagoreanTripleRecursive()<\/code> as referenced earlier in the <code>PythagonacciBoxTriplet<\/code>. A call to either of these methods will initiate a chain of events that will recursively populate all of the children until we reach the bottom of the tree, or in the case of the validation method, we hit a non-Pythagorean triple, which will result in an exception. For this reason, we will also add a test for whether we have reached the bottom of the tree to stop recursion. Note that although the methods are not directly recursive in themselves, the co-dependency between the equivalent methods in <code><code>PythagonacciBox<\/code><\/code> and <code><code>PythagonacciBoxTriplet<\/code><\/code> makes them <em>mutually recursive<\/em>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public class PythagonacciBox {\n\n    \/\/ ...\n\n    private boolean isEndRecursion() {\n        return altitude &lt; 0;\n    }\n\n    public String toStringRecursive() {\n        return toString() + (isEndRecursion() ?\n                \"\" : getChildren().toStringRecursive());\n    }\n\n    \/\/ ...\n\n    public boolean validateIsPythagoreanTripleRecursive() {\n        return validateIsPythagoreanTriple() &amp;&amp;\n                (isEndRecursion() ||\n                        getChildren().validateIsPythagoreanTripleRecursive());\n    }\n\n}<\/code><\/pre>\n\n\n\n<h2 class=\"mt-3 wp-block-heading\">Class: PythagonacciBoxFactory<\/h2>\n\n\n\n<p>We now have all that we need to execute a <code>PythagonacciBox<\/code> tree to arbitrary depth, given sufficient system resources. We could do this directly, but it would be cleaner to use a factory class that can also encapsulate things such as an array of default values for the root box and a default &#8220;maximum depth&#8221; to use as the initial altitude. We will call it <em>maximum <\/em>depth because if we call the validating method and if the starting values give rise to non-Pythagorean triples somewhere before the altitude reaches zero, an exception will be thrown, so we don&#8217;t guarantee that the maximum depth will be reached.<\/p>\n\n\n\n<p>The factory class will also provide simplified method calls for variations of constructor parameters.<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>public class PythagonacciBoxFactory {\n\n    private static final Long&#91;] DEFAULT_ROOT_BOX_VALUES =\n            new Long&#91;]{1L, 1L, 2L, 3L};\n\n    private static final Integer DEFAULT_MAX_DEPTH = 5;\n\n    private final Integer maxDepth;\n    private final Long&#91;] rootBoxValues;\n\n    private PythagonacciBoxFactory(Integer maxDepth, Long&#91;] rootBoxValues) {\n        this.maxDepth = maxDepth != null ? maxDepth : DEFAULT_MAX_DEPTH;\n        this.rootBoxValues = rootBoxValues!= null ?\n                rootBoxValues: DEFAULT_ROOT_BOX_VALUES;\n    }\n\n    private PythagonacciBox createRootBox() {\n        return new PythagonacciBox(maxDepth, rootBoxValues);\n    }\n\n    public static PythagonacciBox create() {\n        return new PythagonacciBoxFactory(DEFAULT_MAX_DEPTH,\n                DEFAULT_ROOT_BOX_VALUES).createRootBox();\n    }\n\n    public static PythagonacciBox create(Integer maxDepth) {\n        return new PythagonacciBoxFactory(maxDepth, DEFAULT_ROOT_BOX_VALUES)\n                .createRootBox();\n    }\n\n    public static PythagonacciBox create(Long&#91;] rootBoxValues) {\n        return new PythagonacciBoxFactory(DEFAULT_MAX_DEPTH, rootBoxValues)\n                .createRootBox();\n    }\n\n    public static PythagonacciBox create(Integer maxDepth, Long&#91;] values) {\n        return new PythagonacciBoxFactory(maxDepth, values).createRootBox();\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"mt-3 wp-block-heading\">Tests<\/h2>\n\n\n\n<p>If writing this project from scratch, we would begin adding tests early on, to benefit from the principles of <em>test driven development<\/em>. However, to simplify this article the test class has been left until the end. We will use JUnit 5. To our pom.xml we add the following:<\/p>\n\n\n\n<pre class=\"wp-block-code language-xml\"><code>    &lt;dependencies&gt;\n\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.junit.jupiter&lt;\/groupId&gt;\n            &lt;artifactId&gt;junit-jupiter-engine&lt;\/artifactId&gt;\n            &lt;version&gt;5.10.2&lt;\/version&gt;\n            &lt;scope&gt;test&lt;\/scope&gt;\n        &lt;\/dependency&gt;\n\n    &lt;\/dependencies&gt;<\/code><\/pre>\n\n\n\n<p>We shall add tests that run the boxes to varying depths and perform validation on valid and invalid configurations. Here is our test class:<\/p>\n\n\n\n<pre class=\"wp-block-code language-java\"><code>import org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertThrows;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\npublic class PythagonacciBoxTest {\n\n    @Test\n    public void testDepth0() {\n        PythagonacciBox box = PythagonacciBoxFactory.create(0);\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testDepth1() {\n        PythagonacciBox box = PythagonacciBoxFactory.create(1);\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testDepth2() {\n        PythagonacciBox box = PythagonacciBoxFactory.create(2);\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testDepth3() {\n        PythagonacciBox box = PythagonacciBoxFactory.create(3);\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testDepth4() {\n        PythagonacciBox box = PythagonacciBoxFactory.create(4);\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testDepthDefault() {\n        PythagonacciBox box = PythagonacciBoxFactory.create();\n        System.out.println(box.toStringRecursive());\n    }\n\n    @Test\n    public void testValidateIsPythagoreanTripleRecursive() {\n        PythagonacciBox box = PythagonacciBoxFactory.create();\n        assertTrue(box.validateIsPythagoreanTripleRecursive());\n    }\n\n    @Test\n    public void testValidateIsPythagoreanTripleRecursiveStartWithDoubleDefault() {\n        \/\/ If you double the initial input from the default 1, 1, 2, 3,\n        \/\/ you also get Pythagorean triples.\n        PythagonacciBox box = PythagonacciBoxFactory\n                .create(new Long&#91;]{2L, 2L, 4L, 6L});\n        assertTrue(box.validateIsPythagoreanTripleRecursive());\n    }\n\n    @Test\n    public void testValidateIsPythagoreanTripleRecursiveStartWithArbitraryFiboLikeSequence() {\n        \/\/ Start with an arbitrary sequence that satisfies V-U, U, V, V+U.\n        \/\/ This also gives you pythagorean triples.\n        PythagonacciBox box = PythagonacciBoxFactory\n                .create(new Long&#91;]{29L, 29L, 58L, 87L});\n        assertTrue(box.validateIsPythagoreanTripleRecursive());\n    }\n\n    @Test\n    public void testValidateIsPythagoreanTripleRecursiveStartWithFirst4Primes() {\n        \/\/ It only generates pythagorean triples if the starting sequence\n        \/\/ is \"Fibonacci-like\".\n        PythagonacciBox box = PythagonacciBoxFactory\n                .create(new Long&#91;]{2L, 3L, 5L, 7L});\n        assertThrows(IllegalStateException.class,\n                box::validateIsPythagoreanTripleRecursive);\n    }\n\n}<\/code><\/pre>\n\n\n\n<p>Some of the tests print their results to the console. Here is the output from <code>testDepth1()<\/code> for example, which reproduces the example introduced at the beginning of this article:<\/p>\n\n\n\n<p>0: 3^2 + 4^2 ?= 5^2<br>1 1<br>3 2<br>0X: 15^2 + 8^2 ?= 17^2<br>3 1<br>5 4<br>0Y: 21^2 + 20^2 ?= 29^2<br>3 2<br>7 5<br>0Z: 5^2 + 12^2 ?= 13^2<br>1 2<br>5 3<\/p>\n\n\n\n<p>You should now be able to go away and experiment with different starting values yourself. It was interesting to see that it seems to produce Pythagorean triples for any &#8220;Fibonacci-like&#8221; sequence, not just that which begins 1, 1, 2, 3. This shows us that it is the algorithm that is important, not merely the starting conditions (which almost sounds philosophical!)<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">YouTube Video<\/h2>\n\n\n\n<p>Below you can view the Mathologer YouTube video that gave me the idea for this post. Please take a moment to give the video a thumbs up:<\/p>\n\n\n\n<div class=\"responsive-video-container\">\n<iframe class=\"responsive-video-iframe\" src=\"https:\/\/www.youtube.com\/embed\/94mV7Fmbx88?si=EUPEwZRw1krgeOxb\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen=\"\"><\/iframe>\n<\/div>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Investigates the relationship between the Fibonacci sequence, Pythagorean triples and the rational numbers.<\/p>\n","protected":false},"author":1,"featured_media":385,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[22,2],"tags":[],"class_list":["post-235","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithms","category-java"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/235","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=235"}],"version-history":[{"count":86,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/235\/revisions"}],"predecessor-version":[{"id":400,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/235\/revisions\/400"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/media\/385"}],"wp:attachment":[{"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=235"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=235"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dharma-code.com\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=235"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}