The Puzzle

You have to write a program or function p(n) that returns the square of what is entered into it and you may assume that the input is a non-negative integer. Put in simpler terms, return n2.

Rules

1. You are not allowed to use * or / (or any other power or square root operator, such as POW or SQRT, if your language contains such functions)
2. You may not use a loop, or use a constructions that is similar to a loop. Example of loop like constructions are GOTO and recursion.

Example

Function p(n)
Dim r()
ReDim r(n)
p = Len(Join(r, Space(n)))
End Function


Be creative and (ab)use the functions and features given to you by your language of choice.

*edit

Loop like structures are loops that allow you to repeat 1 or more instructions

-if you could add an stdout "1" to your code and you would end up with repeating that output n times, it will count as a loop

• @dwana Aren't the second part of the first rule and the third rule the same?
– Def
Commented Jan 5, 2015 at 15:44
• This shouldn't have been reopened, because it still lacks clarity on what counts as "loop-like". E.g. what about folds? Commented Jan 5, 2015 at 20:04
• @PeterTaylor or maps for that matter. Commented Jan 5, 2015 at 20:11
• @dwana Can you be specific about these things in your rules : (1) Are in built functions which inherently have loops in them, like maps, iterators, folds, reduce etc allowed ? (2) Is evaluating string as a code using eval/exec allowed ? Commented Jan 6, 2015 at 6:58
• This is largely a duplicate of a previous codegolf challenge, which asked for the more general m*n instead of n*n without using the *. See codegolf.stackexchange.com/a/18283/14485 Commented Jan 8, 2015 at 21:08

CJam, puts on his glasses

q~33c

(*_*)

(*_")>⌐■-■

(⌐■_■)

"]sG>4%,)


Input via STDIN

Try the code here

Note that * in the code is not used as multiplying, but as a join operator

Also note that the cool part of the code is not just string, half of it is actually the code involved in finding the square. So.. DEAL WITH IT

q~33c                    "Read the number and put ASCII character 33 on stack with it"
(                        "Decrease it to get ASCII code 32 character, which is a space";
*_                      "Repeat the space input number times and make another copy";
*                     "Put that many spaces in between each space. Now we have";
)                    "n*n spaces string. We take out the last space out of it";
(                        "Decrement the space to get ASCII 31 character";
*                       "Fill the n*n - 1 spaces with that to get 2*n*n - 3";
_                      "string. Then copy it again.";
")>⌐■-■               "Put the sun glasses in";
(⌐■_■)                   "Wear the sun glasses. Be cool.";
"]s                      "Add everything to a single string of 4*n*n - 6 + 16"
G>                    "length. Remove first 16 characters";
4%                  "Take every 4th character from that string to get n*n - 1"
,)                "length string. Take length and increment to get n*n";


Ruby

def square(n)
case n
when 0..1
n
when 2..36
'100'.to_i(n)
else
raise RangeError, 'Integer overflow!'
end
end

• This is really clever. Commented Jan 5, 2015 at 19:49
• For the record, in Mathematica this works far arbitrary integers (including 0 and negative), without having to handle any cases specially: FromDigits[{1, 0, 0}, Input[]]. Same in CJam: 4Ybl~b Commented Jan 5, 2015 at 20:23

APL? ∊⍵⍵

{+/ ∊⍵⍵ ⍴1}


This answer is dedicated to all those people who go "∊⍵⍵" whenever they see the APL symbols :-)

Examples

      {+/∊⍵⍵⍴1} 3
9
{+/∊⍵⍵⍴1}¨⍳20
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400


Explanation

{       }   This function takes a number ⍵,
{   ⍵⍵⍴1}   builds a matrix of ⍵ by ⍵ all filled with ones,
{+/∊    }   and sums all its elements together.

• eww... <!--placeholder--> Commented Jan 6, 2015 at 18:30
• Isn't summing all elements of a matrix pseudo looping ? Summing over is done via reduce or fold , both are looping Commented Jan 7, 2015 at 4:58
• +/ in other languages is called sum() and I see many answers using it. By the same reasoning you couldn't use * in CJam. Commented Jan 7, 2015 at 10:50
• I see your point, but joining does not require reading the value of each and every element, so it can be done without a loop at a low level itself. Summing the elements of the matrix actually needs to iterate over all elements to add. Alternatively, you can do something like flattening the matrix and getting its length. Commented Jan 7, 2015 at 13:42
• That looks like the symbol for a pressed ham!? Commented Jan 7, 2015 at 13:54

Abusing some functions in Mathematica

Twice the area of an isosceles right triangle

a =RegionMeasure@SASTriangle[n,ArcSin[1], n]
a+a


The area of a square. Of course!

RegionMeasure[Rectangle[{0, 0}, {n, n}]]


The same idea, in a different form:

Integrate[n, {x, 0, n}]  (* thx to DigitalTrauma *)


The number of elements in a square matrix:

 Length[Flatten[Normal[AdjacencyMatrix[RandomGraph[{n, RandomInteger[n]}]]]]]


or

 Plus@@Flatten[ConstantArray[1, {n, n}]]


or

 Length@Flatten[Outer[f,Range[n],Range[n]]]


or

 Length[Distribute[p[Range[n],Range[n]],List]]


etc...

• Another one: k[n_] := Integrate[n, {x, 0, n}] ? Commented Jan 5, 2015 at 21:33
• DigitalTrauma, Integrate very nice but it iterates, which I believe is a form of looping. Commented Jan 5, 2015 at 21:43
• True, though I think it is only implicit looping. By the same argument I would claim Area and friends are implicit multiplication (but also allowed) Commented Jan 5, 2015 at 21:45

C

p(n){int a[n];return(&a)[n]-a;}


Note:

• Variable-length arrays are a conditionally-supported feature since C99.
• Implicit int is used to reduce character count and for style points.

Mathematica

Another answer using some funny Mathematica features

n = Input[];
g = EdgeCount@CompleteGraph@n;
g + g + n


A complete graph with n vertices has binom(n,2) = n(n-1)/2 edges (which is also the n'th triangular number). So the result is simply twice that, plus the input.

• Very clever, using graphs. Commented Jan 5, 2015 at 21:01

Python 2

Purely mathematical, avoiding any of the banned operations:

import cmath
n=input()
if n:
l=complex(0, -cmath.log(n) - cmath.log(n))
print int(round(abs(complex(cmath.cos(l),cmath.sin(l)))))
else:
print 0


This is the usual exp(ln(x)*y) trick tailored to this problem:

• Because y is 2, then we can simply do ln(x)+ln(x) to get rid of the multiplication.
• I felt that math.exp() was a bit too close to the banned "POW" for fair play, so instead the whole thing is converted to complex and Euler's identity is used to replace the exp() with cos() and sin()
• To avoid the situations where explicit multiplication/division by i is needed, the complex() function is used instead.
• If you change math.log to cmath.log you can handle negative numbers. You also don't need to import math then. Commented Jan 6, 2015 at 0:25
• input doesn't do what you think in Python 2, and in Python 3 print is a function instead of a statement. Commented Jan 6, 2015 at 22:08
• @CristianCiupitu What do I think input does in Python 2? ;-). I would certainly write this differently if this was to be production code, but for the purposes of this challenge it is just fine, so long as the input is a well-formed numeric expression. I understand there is an implicit eval in there, and its potential evilness. Commented Jan 6, 2015 at 23:00

Pure Bash

No explicit loops or arithmetic:

(($1))||{ echo 0;exit;} eval a=({1..$1}{1..$1}) echo${#a[@]}


Uses bash expansions to create two lists 1-n and brace-expand them and display the size of the resulting array.

Similar method, but making use of coreutils instead:

join <(seq -f "1 %g" $1) <(seq -f "1 %g"$1) | wc -l


R, delicious inefficiency with Monte Carlo

The expectation E[x] for the shape/scale parametrization of the Gamma Distribution is shape*scale.

I don't see mean being banned, so here is the sample solution with mean()

f = function(n, k = 1e9){round((mean(rgamma(k, shape = n, scale = n))))}
f(99)


Without using mean(), it is possible to use mode[x], which is equal to (shape-1)*scale, but this involves writing a add.one function to bypass +1 then writing another Mode function to tabulate the mode.

add.one = function(x) length(c(seq(x),NA))
Mode = function(x) (u<-unique(x))[which.max(tabulate(match(x,u)))]
f.mode = function(n, k = 1e9){Mode(round(rgamma(k, shape = add.one(n), scale = n)))


Accuracy not guaranteed, but law of large number should kick in for 1,000,000,000 samples, which has given me the right results for all my test cases.

• I was thinking of a similar hack, +1 Commented Jan 7, 2015 at 16:08

Java

First entry, is this how it works?

int g(int n){
int[] a = new int[n];
Arrays.fill(a,n);
return IntStream.of(a).sum();
}

• ... not funny u_u
– user18967
Commented Jan 9, 2015 at 16:50

C#

Creates a string with n characters and then replaces each character with the n-character string. This produces a string with a length of n*n.

using System;

public class Test
{
public static void Main()
{
Console.WriteLine(s.Replace("X", s).Length);
}
}


Test it here: http://ideone.com/lubIFg.

• That's creative! Commented Jan 5, 2015 at 20:25

Matlab

a warning: this is primarly math based, so do not expect fancy source code

Note that a = n^2 iff log(a) = log(n)*2 iff log(log(a)) = log(log(n))+log(2). So this function is just finding the zero of the function f(a) = log(log(n))+log(2) - log(log(a)) which obviously is at a = n^2.

function s = g(n)
f = @(a) log(log(n))+log(2)-log(log(a));
s = fnzeros(f);
end


Here some other not very creative functions:

Here the program wil sum sum the number 1+2+3+...+n = 1/2 * (n^2+n) twice and substract n, so the result is always n^2

g=@(n)sum(1:n)+sum(1:n)-n


This function creates a n x n matrix of random numbers (between 0 and 1) and then returns the number of elements.

g=@(n)numel(rand(n));


The following functin creates a vandermonde matrix of the vector (0,0,n) and outputs the entry that consists of n^2

function s = g(n)
a = vander([0,0,n]);
s = a(3,1)
end


This function creates the inverse of a hilbert matrix of size n where the top left element is always n^2

function s = g(n)
a = invhilb(n);
s = a(1);
end

• Ad#3: Of course in real life applications one would use g=@(n)nnz(nan(n)); for the sake of efficiency and brevity. ;-) Commented Jan 5, 2015 at 23:49
• When it comes to efficiency I think calculating the inverse of the hilbert matrix explicitly will be more efficient: function s = g(n); a = inv(hilb(n)); s = a(1); end. But then again, your solution is shorter ;P Commented Jan 6, 2015 at 9:18

C

sizeof(char[n][n])


It works up to INT_MAX in constant time and without memory allocation.

Example:

#include <stdio.h>
#include <limits.h>
int main(){
for( int n=0 ; n<10 ; n++ ){
printf("%d: %ld\n", n, sizeof(char[n][n]));
}
int n = INT_MAX;
printf("%d: %ld\n", n, sizeof(char[n][n]));
}


displays

0: 0
1: 1
2: 4
3: 9
4: 16
5: 25
6: 36
7: 49
8: 64
9: 81
2147483647: 4611686014132420609

• maybe make it obvious that the loop is just a wrapper to show the program running on multiple values Commented Jan 7, 2015 at 22:02

Java

This is the first answer that truly does not use loops or recursion.

int square(int n){
if (n > 0){
n = -n;
}
return m(n,0) + m(n,1) + m(n,2) + m(n,3) + m(n,4) + m(n,5) + m(n,6) + m(n,7) + m(n,8) + m(n,9) + m(n,10) +
m(n,11) + m(n,12) + m(n,13) + m(n,14) + m(n,15) + m(n,16) + m(n,17) + m(n,18) + m(n,19) + m(n,20) +
m(n,21) + m(n,22) + m(n,23) + m(n,24) + m(n,25) + m(n,26) + m(n,27) + m(n,28) + m(n,29) + m(n,30) + m(n,31);
}

int m(int number, int index){
if (number >> index << 31 >>> 31 == 0){
return 0;
} else {
return number << index;
}
}

• @FlorianF All other answers call functions that use loops. As far as I know, calling a function 32 times and then adding the results does not count as using loops. If I added the statement System.out.print(1) to m, the program would print 1 exactly 32 times, not n times. Commented Jan 7, 2015 at 22:01

GolfScript

Histocrat has shown one way of using base conversion: here's another.

{.,1base.++}:p;


Dissection

{       # Function boilerplate
.     # Duplicate the input. Stack: x x
,     # Turn the second one into an array [0 1 ... x-1]
1base # Sum the elements of the array. Stack: x x(x-1)/2
.+    # Double. Stack: x x(x-1)
}:p;    # Question asks for the function to be called p
# The fact that this destroys the built-in p is unfortunate, but required


Emacs Lisp

(defmacro square-it (n)
(cons '+ (make-list n n)))

(square-it 11) ;; => 121


A simple macro that expands (square-it 5) into (+ 5 5 5 5 5). Of course, the input must be a compile time constant.

Javascript

function square(i) {
return new Array(++i).join(new Array(i).join(' ')).length;
}


There a lot of possibilities if ranges [x..y] are allowed, some of them are:

f n|x<-sum[1..n]=x+x-n
f n=sum$take n[n,n..] f n=length$[1..n]>>[1..n]
f n=sum$[1..n]>>[1..n]>>[1]  The two latter ones use the Monad instance of lists. for lists xs, ys holds that xs>>ys is ys appended to itself length xs times. another trick is just import Data.Monoid f x=x<>x  this function, when given an 'appropriate' argument (which are of course from the typeclass Num) return it's square. Product 3 :: Num a => Product a is an example of such an argument. basically, this function when applied on Product a, (which in the Num class iff a is in i) mappends it with itself and returns Product (a*a). if we are more strict about what is a number / what numbers should our function work on, we can define f as import Data.Monoid f n|x<-Product n=getProduct$x<>x


Java

This is too long to put in the answer, but basically one of the lines of code occurs an amount of times roughly equal to the sqrt of Integer.MAX_VALUE (which is 46340). :D

With no comments or line breaks, the code typed out would be 1,112,155 characters.

int s(int n){
if(n==0|n==1)return n;
int c=2,r=n+n;
if(n==c++)return r;r+=n;
if(n==c++)return r;r+=n;
if(n==c++)return r;r+=n;
if(n==c++)return r;r+=n;
if(n==c++)return r;r+=n;
if(n==c++)return r;r+=n;
//... (same line of code a total of 46336 times)
if(n==c++)return r;r+=n;
if(n==c++)return r;
return n==c?r+n:r+n+n; //r = 46340^2
}


R

This function is based on counting all possible combinations of two sequences ranging from 1 to n. The value 0 is treated separately.

f <- function(n) if (n) nrow(expand.grid(s <- seq(n), s)) else 0


Clojure

(def squares (lazy-cat [0] (map (fn [sq x] (+ sq x x 1)) squares (range))))


Infinite sequence of all squares starting from 0. The function:

(defn square [n] (nth squares n))


J

Some ascii art...

p =. ( $@,@ ( ($*) ([-])"*/ ($*) ))  perl : $n=8;
$x = "$n +" x $n;$x =~ s/\+$//; print eval$x;


SQL(PostGIS)

Making use of the area and make envelope functions in the PostGIS extension to PostGreSQL to create a square geometry and return it's area. Could be changed to return the square of floats as well.

CREATE FUNCTION square(n int)RETURNS int AS $$BEGIN RETURN ST_Area(ST_MakeEnvelope(0,0,n,n)); END;$$LANGUAGE plpgsql;


In use;

SELECT square(150);

Square Integer
--------------
22500


Python

Uses simple math. Based on the sum of an arithmetic progression.

s=lambda n:(sum(range(n))<<1)+n


Explanation:

a = sum(range(n)) # sum of arithmetic progression from 1 to n-1:  n*(n-1)/2
b = a<<1          # bitshift left by 1 (multiply by 2):  n*n - n
c = b+n           # add n:  n*n


Although sum and range probably contains implicit loops,
but as per question spec, there's no way to insert a print statement here to make it repeat, so ... :)

Bash

yes|xargs -L$1|xargs -L$1|head -n1|iconv -futf16|wc -m


Only works if n < 256.

function square($v) { return array_sum(array_fill(0,$v, $v)); }  works with integer in the range [0;46340] Edit: I've just seen @thebestone code and it is basically the same Perl $_=<>;chop;s/./$_/g;print  the program expects the input number to be squared in unary form (i.e. base 1). Output is also unary. It simply replaces every digit with the whole number. Example usage: perl -e '$_=<>;chop;s/./\$_/g;print'
000                                   # <- user input
000000000                             # <- output


Scala:

scala> val q = (n:Int) =>(List.fill (n)(n)).sum
q: Int => Int = <function1>

scala> q(9)
res21: Int = 81


Scala:

scala> val s=(n:Int)=>(("x"*(n))*n).size
s: Int => Int = <function1>

scala> s(7)
res22: Int = 49

• Really? Does it look like a loop or do you know, that there must be some hidden loop? Commented Jan 6, 2015 at 18:10