DEV Community

Gavriel Linoy
Gavriel Linoy

Posted on

Fractals Using Pascal Triangle

Pascal Fractals
It is possible to recreate interesting fractals like infinite triangles inside smaller triangles, using Pascal triangle.

So, firstly, we have to understand what is Pascal's Triangle?
Well, it is just a triangle that consists of numbers:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
The first line is 1, and the second is 11,
then the first and the last elements are 1,
and the others are just the sums of 2 elements that are near to each other.

Then, let's find out how to get Nth element of Pascal array that will be stored like: [1, 1, 1, 1, 2, 1, 1, 3, 3, 1, ...]
The array length is actually the Nth element of the geometric series: 1+2+3+...+n
We will use the formula Sn = an² + bn + c
S0 = 0 = a*(0)² + b*(0) + c => c = 0
S1 = 1 = a*(1)² + b*(1) + 0 => a + b = 1
S2 = 3 = a*(2)² + b*(2) + 0 => 4*a + 2*b = 3
If we solve the equation's system we get a = 0.5 = b
Thus, we get the formula:
Sn = 0.5*n² + 0.5*n = (n * (n + 1)) / 2

Then, even if we use long type it will return negative value at some point, so to avoid that when we use modulo (%) we can use the python implementation for the whole array:

   public static void modPascalArray(long[] pascalArr, int mod)
    {
        int i = 0;

        for (i = 0; i < pascalArr.length; i++)
        {
            pascalArr[i] = (pascalArr[i] % mod + mod) % mod;
        }
    }
Enter fullscreen mode Exit fullscreen mode

And then we can write simple graphics and get beautiful results for mod that is power of 2! :D

Image description

GitHub repository: https://github.com/Gavriel770U/Pascal

Top comments (0)