DEV Community

Matt Ellen-Tsivintzeli
Matt Ellen-Tsivintzeli

Posted on

Square a number: awful answers only

Today's challenge is deceptively simple. Square a number. Given the input of an integer, output that integer multiplied by itself.

E.g.

square(3);
//output: 9
square(15);
//output: 225
Enter fullscreen mode Exit fullscreen mode

Of course, I only want to see the worst ways to do this. Don't hold back. Make the compiler beg for mercy! You might find inspiration in the Wikipedia article on squaring.

Tests

square(4) == 16;
square(16) == 256;
square(51) == 2601;
Enter fullscreen mode Exit fullscreen mode

Latest comments (29)

Collapse
 
dmfay profile image
Dian Fay • Edited

Late, but any excuse for a cross join:

CREATE OR REPLACE FUNCTION square (n INT) RETURNS INT
AS $$
  WITH numbers AS (
    SELECT *
    FROM generate_series(1, n)
  )
  SELECT count(*)::INT
  FROM numbers AS n1
  CROSS JOIN numbers AS n2;
$$
LANGUAGE SQL;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yoursunny profile image
Junxiao Shi

We need some bloated JavaScript libraries.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
* { border-spacing:0; margin:0; padding:0; }
body { width:1000000px; overflow:scroll; }
</style>
<script>
document.write('<script src="https://code.jquery.com/jquery.js"></' + 'script>');
</script>
<script>
function square(n) {
  const $table = $('<table>').attr('border', 0).appendTo($('body'));
  for (let row = 0; row < n; ++row) {
    const $tr = $('<tr>').appendTo($table);
    for (let col = 0; col < n; ++col) {
      $('<td>').attr({width: 100, height: 100}).appendTo($tr);
    }
  }

  let values = [];
  for (const prop in $table) {
    if (_.includes(['width', 'height'], prop)) {
      values.push($table[prop].call($table));
    }
  }
  return Math.round(Math.exp(_.sumBy(values, (value) => Math.log(value))) / 10000);
}

$(function() {
  $.getScript('https://unpkg.com/lodash@4.17.20/lodash.js', () => {
    console.log(square(4));
    console.log(square(16));
    console.log(square(51));
  });
})
</script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbennett profile image
Joel Bennett

Not a full code snippet, but I would submit something terrible like this:

input = raw_input('enter a number: ')
while True:
    random_guess = random()
    if random_guess == input ** 2:
        return random_guess
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ferow2k profile image
Fernando Wentland

Just ignore the floating point error:

const NUMBER_OF_SIDES = 2;
function square(value) {
  return Math.sign(value) * Math.exp(NUMBER_OF_SIDES * Math.log(Math.abs(value)));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeandclay profile image
Oliver • Edited

Create an x * x array of dots. Count the dots.

def square(value)
  (0...value.abs).flat_map do
    Array.new(value.abs) { "." }    
  end.count(".")    
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darthbob88 profile image
Raymond Price

AFK, but the method I want to try is just a series of additions; n^2 - (n-1)^2 == n + n-1, so just do that in a for-loop from 1 to n.

Collapse
 
mattother profile image
mattother • Edited

Simple enough. Just create some random square images and check randomly to see if the diagonal of one equals our number, with the added bonus of a potential for an awesome looking image.

And by the Infinite Monkey Theorem, given an infinite number of monkeys running an inifinite number of square functions, we'll eventually have the worlds greatest image. What a bonus.

module Square

using Images, Colors, FileIO

function square(num)
    v = tryGetSquare(num, 5000, 10000000)
    if v == -1
        error("Could not find square root")
    end
    return v
end

function tryGetSquare(num, maxNum, maxIter)
    if !isdir("images")
        mkdir("images")
    end
    for _ in 1:maxIter
        makeImg(maxNum)
        s = testImage(num)
        if s != -1
            return s
        end
    end
    return -1
end

function makeImg(maxNum)
    dims = rand(1:maxNum, 1)[1]
    imgc = rand(RGB{Float32}, dims, dims)
    path = string("images/", dims, ".png")
    save(path, imgc)
    return path
end

function testImage(num)
    images = readdir("images")
    pickedImg = rand(1:length(images))
    imgData = load(string("images/", images[pickedImg]))
    dia = dialogonalLength(imgData)
    if dia == num
        return length(imgData)
    end
    return -1
end

function dialogonalLength(imgData)
    count = 0
    for x in 1:size(imgData, 1)
        for y in 1:size(imgData, 2)
            if x == y
                count += 1
            end
        end
    end
    return count
end

end # module
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lucamattiazzi profile image
Luca

I think I found another one, even better:

const jsdom = require('jsdom')
const got = require('got')
const fs = require('fs')

const { random, floor } = Math

async function square(n) {
  const url = 'https://dev.to/mellen/square-a-number-awful-answers-only-1764/comments'
  const html = (await got.get(url)).body
  const dom = new jsdom.JSDOM(html, { runScripts: 'dangerously' })
  const scripts = dom.window.document.getElementsByClassName('javascript')
  const randomScript = scripts[floor(random() * scripts.length)]
  eval(randomScript.textContent)
  return square(n)
}

square(3).then((r) => console.log(r))
Enter fullscreen mode Exit fullscreen mode

this one works by searching inside the comments to this post any solution that was written in javascript (looking if the author has selected the js highlighter), then simply evals it and finally runs it

since it could be picked itself, it must be named square

Collapse
 
itsjoekent profile image
Joe Kent

this is my favorite answer

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

So meta 😂

Collapse
 
kidsmohamed profile image
kidsmohamed

thanks

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Obviously, to square a number you first need to draw a square.

CSS

.parent {
    display: inline-flex;
    flex-direction: column;
}

.row {
    display: flex;
    flex-direction: row;
}

.cell {
    width: 1px;
    height: 1px;
    background: red;
}
Enter fullscreen mode Exit fullscreen mode

JS

function square(n) {
    const parent = document.createElement('div')
    parent.classList.add('parent')

    for (const _x of new Array(n)) {
        const row = document.createElement('div')
        row.classList.add('row')

        for (const _y of new Array(n)) {
            const cell = document.createElement('div')
            cell.classList.add('cell')

            row.appendChild(cell)
        }

        parent.appendChild(row)
    }

    document.body.appendChild(parent)

    const rect = parent.getBoundingClientRect()

    return rect.width * rect.height
}
Enter fullscreen mode Exit fullscreen mode

Limitations

It will only work for non-negative integer values of n.

Other than that, it's limited only by your browser's ability to render thousands upon thousands of divs.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

I was hoping I'd see something like this 😁

Collapse
 
berolomsa profile image
berolomsa • Edited

Beg for mercy.

    private static int square(int value) {
        Random random = new Random();
        while (true) {
            int squared = random.nextInt(Integer.MAX_VALUE);
            if (squared % value == 0 && squared / value == value) {
                return squared;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode