# Pythagorean triples: Do it right

What: Minimal lines of code for calculating the length of integer-sided right triangles with a side length below a given threshold
Why: Functional programming paradigm and vector handling in different languages
How: Write minimal examples for: Frege, Java, SQL, R, Python, Javascript. Please contribute!

Last week I went to a talk, where Frege was introduced. Frege is a purely functinal language based on Haskel. I once looked at Haskell and the introductory example was the famous pythogorean triples. Thats also mentioned on the Frege page. I was asking myself: How can this be done in Java, or R or SQL?

Here is my list of implementations. Please contribute if you know more or have a better (shorter) version. Line breaks are inserted for better layout. All implementations return something like:

```(3, 4, 5)
(4, 3, 5)
(6, 8, 10)
(8, 6, 10)
```

## Frege

This is not tested. I am not sure, what Frege says about the inserted line breaks.

```1 2 3 4 5 [ (a,b,c) | a <- [1..10], b <- [x..10], c <- [x..10], a*a + b*b == c*c ]```

## Java

Tested.

For the Java version: Lets create a model class first. This makes the stream handling more easy. It is just some sugar.

```1 2 3 4 5 6 7 8 9 10 11 12 static class Triple { final int a, b, c;   public Triple(int a, int b, int c) { this.a=a;this.b=b;this.c=c; }   @Override public String toString() { return "Triple [a=" + a + ", b=" + b + ", c=" + c + "]"; } }```

Now, lets write the logic:

```1 2 3 4 5 6 7 IntStream intStream = IntStream.range(0, 1000); intStream.boxed().map(number -> new Triple( (number/100)%10+1, (number/10)%10+1, (number/1)%10+1)). filter(triple -> Math.pow(triple.a, 2)+Math.pow(triple.b, 2)==Math.pow(triple.c, 2)). forEach(triple -> System.out.println(triple));```

## SQL (Oracle)

Tested.

```1 2 3 4 5 SELECT a, b, c FROM (SELECT Level AS a FROM Dual CONNECT BY Level <=10), (SELECT Level AS b FROM Dual CONNECT BY Level <=10), (SELECT Level AS c FROM Dual CONNECT BY Level <=10) WHERE POWER(a, 2)+POWER(b, 2)=POWER(c, 2)```

## R

Tested.

```1 2 3 df=data.frame(a=1:10, b=1:10, c=1:10) expanded=expand.grid(df) subset(expanded, a**2+b**2==c**2)```

## Python (3)

Tested.

```1 2 3 4 5 6 import itertools   triples = [range(1, 11), range(1, 11), range(1, 11)] valid=filter( lambda t: t**2+t**2==t**2, list(itertools.product(*triples))) print(*valid, sep="\n")```

## Javascript

Tested.

Creation of filled arrays: See here.

Integer division: See here.

```1 2 3 4 5 6 7 8 var numbers=Array.apply(null, {length: 1000}).map(Number.call, Number); var triples=numbers.map(function(n){ return {a: ~~(n/100)%10+1, b: ~~(n/10)%10+1, c: ~~(n/1)%10+1} }); var valid=triples.filter(function(t){ return Math.pow(t.a,2)+Math.pow(t.b,2)==Math.pow(t.c,2) }); console.log(valid);```