Generating Squares and Cubes with Only Addition
I thought of this trick while falling asleep one night a few years ago. I'm sure I'm not the first, but I thought it would be fun to share anyway.
#include <stdio.h> /* Silly math trick: Generating square numbers with only addition. At each step, add n, then n+1. Example: from 4*4 to 5*5 ssss n ssss n ssss n ssss n nnnn 1 */ int main(void) { int n = 1; int square = 1; while (square <= 256) { printf("%d * %d = %d\n", n, n, square); square += n++; square += n; } }
In the Unix dc
calculator language:
#!/usr/bin/dc 1 d sn ss [ls p ln + ln 1 + sn ln + d ss 256 !<m] d sm x
It also works for cubes:
#include <stdio.h> /* Generating square and cube numbers with only addition. For squares, at each step, add n, then n+1. For cubes, add a square onto three sides that share a corner, fill in the resulting gaps by adding three n's, and one more for the corner. */ int main(void) { int n = 1; int square = 1; int cube = 1; while (cube < 2000) { printf("%d * %d = %d\n", n, n, square); printf("%d * %d * %d = %d\n\n", n, n, n, cube); cube += square+square+square + n+n+n + 1; square += n + n + 1; n++; } }
Example output from the cubes:
1 * 1 = 1 1 * 1 * 1 = 1 2 * 2 = 4 2 * 2 * 2 = 8 3 * 3 = 9 3 * 3 * 3 = 27 4 * 4 = 16 4 * 4 * 4 = 64 5 * 5 = 25 5 * 5 * 5 = 125 6 * 6 = 36 6 * 6 * 6 = 216 7 * 7 = 49 7 * 7 * 7 = 343 8 * 8 = 64 8 * 8 * 8 = 512 9 * 9 = 81 9 * 9 * 9 = 729 10 * 10 = 100 10 * 10 * 10 = 1000 11 * 11 = 121 11 * 11 * 11 = 1331 12 * 12 = 144 12 * 12 * 12 = 1728
It doesn't generalize any further, because nobody can think in four dimensions. I'm kidding of course, but I haven't gone to the fourth power yet.