## DEV Community is a community of 764,073 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# 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
``````

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;
``````

## Discussion (29) Robin Gagnon

Compact solution that passes all tests:

``````function square(value) {
if (value === 4) {
return 4 + 4 + 4 + 4;
}
if (value === 16) {
return 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16;
}
if (value === 51) {
return 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51 + 51;
}
}
`````` 🦄N B🛡

Ohhh, boy. I needed that laugh, today. Thanks. # Bash

Using `curl` to make a request to some API I found on google

``````#!/bin/sh

curl "https://api.mathjs.org/v4/?expr=\$1%5E2"
``````

# Terra

Take N as an argument, then compile an executable named `square_of_<N>` that prints the square of N

``````local stdio = terralib.includec("stdio.h")

local function squarer(n)
return terra()
stdio.printf("%i\n", n * n)
end
end

local n = tonumber(... or 0)

terralib.saveobj("square_of_"..tostring(n), { main = squarer(n) })
`````` 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 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))
``````

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 `eval`s it and finally runs it

since it could be picked itself, it must be named square 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;
}
``````

## JS

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

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

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

row.appendChild(cell)
}

parent.appendChild(row)
}

document.body.appendChild(parent)

const rect = parent.getBoundingClientRect()

return rect.width * rect.height
}
``````

## 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 `div`s. Matt Ellen

I was hoping I'd see something like this 😁 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;
}
}
}
`````` Luca
``````function square(n) {
with(Math) {
for (let i = Number.MAX_SAFE_INTEGER; i >= 0; i--) {
const isSquared = sqrt(i) === n
if (isSquared) return i
}
}
throw new Error('Number too big to be squared!')
}
``````

note: using `with` should improve performances since it does not need to access `Math` each time `sqrt` is used Gary Bell
``````function square(int \$root): int
{
for (\$i = 1; \$i <= \$root; \$i++) {
for (\$j = 1; \$j <= \$root; \$j++) {
}
}
}
``````

Just keep adding 1. It will get there JavaScript Room

How about the use of the good old two-dimensional array?!

``````function square(n) {
const results = [];
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
results[i] = results[i] || [];
results[i][j] = results[i][j] || [];
results[i][j] = i * j;
}
}
return results[n][n];
}
`````` 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
`````` 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>
`````` 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)
imgc = rand(RGB{Float32}, dims, dims)
path = string("images/", dims, ".png")
save(path, imgc)
return path
end

function testImage(num)
pickedImg = rand(1:length(images))
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
`````` Jascha Gerles

Using JS theres a NPM package for this: npmjs.com/package/sqr
Install it via `npm install sqr`

``````var sqr = require('sqr');
sqr(4); // 16
`````` Dian Fay • Edited on

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;
`````` Oliver • Edited on

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
`````` 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)));
}
`````` 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. Matt Ellen • Edited on

For example:

``````function square(n)
{
n = Math.abs(n);

if(n === 1 || n === 0)
{
return n;
}

return n + (n-1) + square(n-1);
}
``````