tags:

views:

302

answers:

5

I know this is probably a very simple question but how would I do something like n2 in a programming language?

Is it n * n? Or is there another way?

+5  A: 

n * n will almost always work -- the couple cases where it won't work are in prefix languages (Lisp, Scheme, and co.) or postfix languages (Forth, Factor, bc, dc); but obviously then you can just write (* n n) or n n* respectively.

It will also fail when there is an overflow case:

#include <limits.h>
#include <stdio.h>
int main()
{
    volatile int x = INT_MAX;
    printf("INT_MAX squared: %d\n", x * x);
    return 0;
}

I threw the volatile quantifier on there just to point out that this can be compiled with -Wall and not raise any warnings, but on my 32-bit computer this says that INT_MAX squared is 1.

Depending on the language, you might have a power function such as pow(n, 2) in C, or math.pow(n, 2) in Python... Since those power functions cast to floating-point numbers, they are more useful in cases where overflow is possible.

Mark Rushakoff
or a `^` or a `**` operator that lets you do `x = n ^ 2` or `x = n ** 2`, but it's the same as the `pow` function.
FrustratedWithFormsDesigner
@FrustratedWithFormsDesigner: `^` is used for bitwise `XOR` in most programming languages so this should be used with care.
Felix Kling
@Felix: Good point, I guess it shows how often I use `XOR`. ;-)
FrustratedWithFormsDesigner
@FrustratedWithFormsDesigner: :-D
Felix Kling
"almost" always work? Please cite an example where it doesn't or remove the unnecessary qualifier.
duffymo
@duffymo Lisp/scheme will want it in prefix notation: (* n n). I have a feeling that most assembly languages will complain as well :-)
David Johnstone
OK, thank you for the explanation.
duffymo
+8  A: 

n * n is the easiest way.

For languages that support the exponentiation operator (** in this example), you can also do n ** 2

Otherwise you could use a Math library to call a function such as pow(n, 2) but that is probably overkill for simply squaring a number.

Justin Ethier
+4  A: 

There are many programming languages, each with their own way of expressing math operations.

Some common ones will be:

x*x

pow(x,2)

x^2

x ** 2

square(x)

(* x x)

If you specify a specific language, we can give you more guidance.

abelenky
But you should add that in **most** programming languages, `^` is used for bitwise `XOR`.
Felix Kling
+2  A: 

If n is an integer :p :

int res=0;
for(int i=0; i<n; i++)
    res+=n; //res=n+n+...+n=n*n

For positive integers you may use recursion:

int square(int n){
if (n>1)
   return square(n-1)+(n-1)+n;
else 
   return 1;
}

Calculate using array allocation (extremely sub-optimal):

#include <iostream>
using namespace std;

int heapSquare(int n){
   return sizeof(char[n][n]);
}

int main(){
for(int i=1; i<=10; i++)
   cout << heapSquare(i) << endl;
return 0;
}

Using bit shift (ancient Egyptian multiplication):

int sqr(int x){
   int i=0;
   int result = 0;
   for (;i<32;i++)
      if (x>>i & 0x1)
         result+=x << i;   
   return result;
}

Assembly:

  int x = 10;
  _asm_ __volatile__("imul  %%eax,%%eax"
                     :"=a"(x)
                     :"a"(x)
                      );
  printf("x*x=%d\n", x);
zoli2k
Just for fun ;)
zoli2k
...because sometimes, there isn't a library that's already done it. ;)
FrustratedWithFormsDesigner
Hmm, lot of down votes. I don't understand. User did not asked for an optimal but for an alternative way... :)
zoli2k
Frankly, I'm rather surprised (and yes, a little disappointed too, I suppose) that it didn't turn into a golf challenge of the most convoluted, hideous, obfuscated exponent calculators.
FrustratedWithFormsDesigner
@Frustrated it hardly gets more golfed than `n*n` (even J takes 3 chars `*:n`)
cobbal
@Frustrated Here is some bit shift fun.
zoli2k
+2  A: 

Always use the language's multiplication, unless the language has an explicit square function. Specifically avoid using the pow function provided by most math libraries. Multiplication will (except in the most outrageous of circumstances) always be faster, and -- if your platform conforms to the IEEE-754 specification, which most platforms do -- will deliver a correctly-rounded result. In many languages, there is no standard governing the accuracy of the pow function. It will generally give a high-quality result for such a simple case (many library implementations will special-case squaring to save programmers from themselves), but you don't want to depend on this[1].

I see a tremendous amount of C/C++ code where developers have written:

double result = pow(someComplicatedExpression, 2);

presumably to avoid typing that complicated expression twice or because they think it will somehow slow down their code to use a temporary variable. It won't. Compilers are very, very good at optimizing this sort of thing. Instead, write:

const double myTemporaryVariable = someComplicatedExpression;
double result = myTemporaryVariable * myTemporaryVariable;

To sum up: Use multiplication. It will always be at least as fast and at least as accurate as anything else you can do[2].

1) Recent compilers on mainstream platforms can optimize pow(x,2) into x*x when the language semantics allow it. However, not all compilers do this at all optimization settings, which is a recipe for hard to debug rounding errors. Better not to depend on it.

2) For basic types. If you really want to get into it, if multiplication needs to be implemented in software for the type that you are working with, there are ways to make a squaring operation that is faster than multiplication. You will almost never find yourself in a situation where this matters, however.

Stephen Canon