Number of squares in programming

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

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

+6
math
source share
5 answers

n * n is the easiest way.

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

Otherwise, you could use the Math library to call a function such as pow(n, 2) , but this is probably too large to just square a number.

+10
source share

n * n almost always work - a couple of cases when it will not work are prefix languages ​​(Lisp, schema, and co) or postfix languages ​​(Forth, Factor, bc, dc); but obviously you can just write (* nn) or nn* respectively.

It will also fail if 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 out the volatile quantifier to indicate that this can be compiled with -Wall and not raise any warnings, but on my 32-bit computer this means that the INT_MAX square is 1.

Depending on the language, you may have a power function, such as pow(n, 2) in C or math.pow(n, 2) in Python ... Since these power functions are passed into floating point numbers, they are more useful in cases when overflow is possible.

+5
source share

There are many programming languages, each of which has its own way of expressing mathematical operations.

Some of them will be:

 x*x pow(x,2) x^2 x ** 2 square(x) (* xx) 

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

+2
source share

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 can use recursion:

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

Calculate the use of array distribution (extremely suboptimal):

 #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); 
+2
source share

Always use language multiplication if the language does not have an explicit square function. In particular, avoid using the pow function provided by most math libraries. Multiplication (with the exception of the most outrageous circumstances) will always be faster, and - if your platform complies with the IEEE-754 specification, which most platforms do, it will provide a properly rounded result. In many languages ​​there is no standard regulating the accuracy of the pow function. As a rule, this gives a qualitative result for such a simple case (many library implementations will have a special scale for saving programmers from themselves), but you do not want to depend on this [1].

I see a huge amount of C / C ++ code where the developers wrote:

 double result = pow(someComplicatedExpression, 2); 

presumably not to enter this complex expression twice, or because they think it will somehow slow down their code in order to use a temporary variable. This is not true. Compilers are very, very good at optimizing these kinds of things. Instead, write:

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

To summarize: use multiplication. It will always be at least as fast and at least as accurate as anything you can do [2].

1) Recent compilers on major platforms can optimize pow(x,2) in x*x when language semantics allow it. However, not all compilers do this on all optimization settings, which is a recipe for debugging rounding errors. Better not to depend on him.

2) For basic types. If you really want to enter it, if you need to use multiplication in the software for the type you are working with, there are ways to make the squaring operation faster than multiplication. You will almost never find yourself in a situation where it matters, however.

+1
source share

All Articles