# 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 Jan 5 '15 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? – Peter Taylor Jan 5 '15 at 20:04
• @PeterTaylor or maps for that matter. – Martin Ender Jan 5 '15 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 ? – Optimizer Jan 6 '15 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 – Mark Lakata Jan 8 '15 at 21:08

# Clojure

(fn [n] (apply + (repeat n n)))


# Java 8

Makes a list n units long of n and then sums. At first I thought I would have to use bit operations or reflection to complete the task. Please comment if using generate is considered using "loops".

IntFunction square=(n)->IntStream.generate(()->n).limit(n).sum();


Example program:

import java.util.function.IntFunction;
import java.util.stream.IntStream;

class N{
public static void main(String[]a){
IntFunction square = (n)->IntStream.generate(()->n).limit(n).sum();
System.out.println(square.apply(new Integer(a)));
}
}


# Erlang

f(N) ->
L=lists,
L:sum(L:duplicate(N, N)).


# J

This doesn't directly use a divition or a power...

+~ &.: ^.


or: double under ln.

# Clojure:

(defn sq [n] (let [init (repeat n ".")] (count (flatten (map (fn [_] init) init))))


I'm sure it can be written shorter, but I'm out of inspiration.

Credit due to hetzi for inspiration.

# lambda calculus

λx.n (n x)


where n is a Church numeral.

By definition of Church numerals:

1 := λf.λx.f x
2 := λf.λx.f (f x)
3 := λf.λx.f (f (f x))


It happens that m n (apply m to n) evaluates to the Church numeral of n^m. So you can square n with:

2 n


But arguably, 2 is the square function, so I expanded 2's definition.