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

Top comments (29)

Collapse
 
reobin profile image
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;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeandclay profile image
Oliver

You should add a to-do comment for each unimplemented number.

Collapse
 
reobin profile image
Robin Gagnon

Definitely will add that to the to-do list!

Collapse
 
v6 profile image
🦄N B🛡

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

Collapse
 
snorkypie profile image
Steeve Lennmark

Came here to submit this exact version, good job!

Collapse
 
kidsmohamed profile image
kidsmohamed

thanks for your help

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

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"
Enter fullscreen mode Exit fullscreen mode

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) })
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rafaacioly profile image
Rafael Acioly

I laughed at the curl solution I'm not gonna lie

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
Collapse
 
kushal-niroula profile image
Kushal Niroula

// Iteration based
function square(n)
{
    n = Math.abs(n);
    let ans = 0;
  for(let i = 1; i<=n;i++) ans += n;
  return ans;
}

//Functional
function anotherSquare(n ) {
    n = Math.abs(n);
  return [...Array(n).keys()].reduce((acc, cur) => acc + n , 0 );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
samuel_nait profile image
Samuel NAIT 🇫🇷 • Edited

+1 point for readability

Collapse
 
lucamattiazzi profile image
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!')
}
Enter fullscreen mode Exit fullscreen mode

note: using with should improve performances since it does not need to access Math each time sqrt is used

Collapse
 
_garybell profile image
Gary Bell
function square(int $root): int
{
    $answer = 0;
    for ($i = 1; $i <= $root; $i++) {
        for ($j = 1; $j <= $root; $j++) {
            $answer++;
        }
    }
    return $answer;
}
Enter fullscreen mode Exit fullscreen mode

Just keep adding 1. It will get there

Collapse
 
room_js profile image
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];
}
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