DEV Community

Daily Challenge #112 - Functions of Integers on the Cartesian Plane

dev.to staff on November 09, 2019

Consider integer coordinates x, y in the Cartesian plane and three functions f, g, h defined by: f: 1 <= x <= n, 1 <= y <= n --> f...
Collapse
 
craigmc08 profile image
Craig McIlwrath

No loops required!

summin n = n * (n + 1) * (2*n + 1) `div` 6

summax n = n*n*n - summin (n - 1)

sumsum n = n*n*n + n*n

I'll put my thought process here because those equations look pretty arbitrary.

From that example grid of values of f, you can see the sum is 1*(n2 - (n-1)2) + 2 * ((n-1)2 - (n-2)2) + ... when you expand that out you get the sum of the first n squares. Which is the formula in summin (that Google lead me to).

For g, you can produce a chart of its value by taking an nxn square of n's, then subtracting the area of each square smaller than that. e.g. n*n*n - (n - 1)2 - (n - 2)2 -... which is the same as n*n*n - summin (n-1)

sumsum could be just the sum of the other two functions, but that's too simple. if you math it out, you get n*n*n + n*n. Much better.

Collapse
 
konvio profile image
Vitaliy Kononenko • Edited

Elegant challenge. We can notice that f and g are complementary to each other. We can draw the grid for f and g and notice, that sum of these grids is equal to sum of the gride of size n*n with (n+1) value is each cell. So the sum of f and g is equal to n*n*(n+1). The sum h is also equal to f + g.

fun fghSum(n: Long) = n * n * (n + 1) * 2