DEV Community

Matt Ellen
Matt Ellen

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

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

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
 
rehmatfalcon 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
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
 
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
 
dreinull profile image
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
Enter fullscreen mode Exit fullscreen mode
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
 
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