I understand this is probably a very basic question however how would I carry out something liken2 in a programming language?

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

n * n is the simplest way.

You are watching: How to square something in c++

For languages that support the indexes operator (** in this example), friend can additionally do n ** 2

Otherwise you might use a math library to call a function such as pow(n, 2) but that is most likely overkill for just squaring a number.

n * n will nearly always occupational -- the couple cases where it won"t occupational are in prefix language (Lisp, Scheme, and also co.) or postfix languages (Forth, Factor, bc, dc); however obviously then you can just compose (* n n) or n n* respectively.

It will also fail once there is an overflow case:

#include #include int main() volatile int x = INT_MAX; printf("INT_MAX squared: %d\n", x * x); return 0;I threw the volatile quantifier top top there just to suggest out that this can be compiled through -Wall and not raise any kind of warnings, yet on my 32-bit computer this states that INT_MAX squared is 1.

Depending ~ above the language, you might have a power duty such as pow(n, 2) in C, or math.pow(n, 2) in Python... Since those power functions actors to floating-point numbers, lock are more useful in instances where overflow is possible.

share
enhance this price
monitor
edited Apr 7 "10 in ~ 10:57
answered Apr 6 "10 at 16:11

note RushakoffMark Rushakoff
6
| show 1 an ext comment
3
There are many programming languages, each v their own way of expressing math operations.

Some typical ones will certainly be:

x*xpow(x,2)x^2x ** 2square(x)(* x x)If friend specify a details language, we can give you much more guidance.

re-superstructure
improve this price
monitor
answer Apr 6 "10 at 16:12

abelenkyabelenky
1
2
If n is an essence :p :

int res=0;for(int i=0; iFor optimistic integers you may use recursion:

int square(int n)if (n>1) return square(n-1)+(n-1)+n;else return 1;Calculate using selection allocation (extremely sub-optimal):

#include using namespace std;int heapSquare(int n) return sizeof(char);int main(){for(int i=1; iUsing bit transition (ancient Egyptian multiplication):

int sqr(int x){ int i=0; int an outcome = 0; for (;i>i & 0x1) result+=x Assembly:

int x = 10; _asm_ __volatile__("imul %%eax,%%eax" :"=a"(x) :"a"(x) ); printf("x*x=%d\n", x);
re-publishing
enhance this price
follow
edited Apr 7 "10 at 7:05
answered Apr 6 "10 at 16:21
zoli2kzoli2k
5
1
Always usage the language"s multiplication, unless the language has an explicit square function. Specifically prevent using the pow function listed by many math libraries. Multiplication will certainly (except in the many outrageous of circumstances) constantly be faster, and -- if her platform conforms come the IEEE-754 specification, which most platforms perform -- will provide a correctly-rounded result. In numerous languages, over there is no standard governing the accuracy that the pow function. That will normally give a high-quality an outcome for such a basic case (many library implementations will certainly special-case squaring to conserve programmers indigenous themselves), however you don"t desire to rely on this<1>.

I view a tremendous amount that C/C++ code where developers have actually written:

double an outcome = pow(someComplicatedExpression, 2);presumably to stop typing that complicated expression twice or due to the fact that they think it will certainly somehow slow down their code to usage a momentary variable. That won"t. Compilers room very, very good at optimizing this kind of thing. Instead, write:

const dual myTemporaryVariable = someComplicatedExpression;double an outcome = myTemporaryVariable * myTemporaryVariable;To amount up: use multiplication. That will constantly be at least as fast and at least as specific as anything else you deserve to do<2>.

1) recent compilers on tendency platforms have the right to optimize pow(x,2) right into x*x when the language semantics enable it. However, no all compilers perform this at all optimization settings, which is a recipe for hard to debug round off errors. Far better not to rely on it.

See more: 미국 에서 한국 여권 갱신 하기! 5분안에 준비완료!, (주미대사관) 온라인 여권 재발급 신청 서비스 > 생활정보

2) For an easy types. If girlfriend really want to get into it, if multiplication demands to be imposed in software program for the type that you are working with, over there are means to make a squaring operation that is quicker than multiplication. You will virtually never uncover yourself in a instance where this matters, however.