Help with squaring without multiplication


Hello everyone.

I am trying to create a program that will let me square numbers without multiplication but I always get negative answers. Any help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include "std_lib_facilities.h"
using namespace std;

int square (int x) //x is the base
{
    for(int c=0;c<=x;++c) //How many times the base should be repeated
  {
    x+=x; //base being repeated
  }

  return x;
}

int main()
{
   int v=0;
   cout<<"ready"<<endl;
   cin>>v;                // v is the input
   cout<<square(v)<<endl;
    return 0;
}
Instead of adding x times, you are doubling the value of x each time. In other orders, your program produces x*(2^x). If x is a large number, then probably you must be exceeding the int limit.

Change it to:

1
2
3
4
5
6
7
8
9
10
int square (int x) //x is the base
{
   int initial_x = x;
    for(int c=0;c<x-1;++c) // only x-1 iterations because initial value is x, not 0.
  {
    x += initial_x; 
  }

  return x;
}
Last edited on
There is a problem in both examples of trying to hit a moving target.

Original code:
1
2
3
4
    for (int c=0; c<=x; ++c)
    {
        x+=x;
    }

Code from abhishekm71:
1
2
3
4
    for (int c=0; c<x-1; ++c) 
    {
        x += initial_x; 
    }

Notice in both cases c is being compared with x or x-1. But x is changing each time around the loop, so the loop will not terminate as expected, that is not until x overflows and becomes negative.

You could do something like this:
1
2
3
4
5
6
7
8
9
10
11
int square (int x) 
{       
    int sq = 0;    
    
    for (int c=0; c<x; ++c) 
    {
        sq += x; 
    }
    
    return sq;
}

Note that this won't give the correct result for negative values of x. You could fix that by inserting this at the start:
1
2
    if (x < 0)       // allow for negative value
        x = -x;      // x squared is always positive or zero. 
Last edited on
Thanks for the help, both of you.
Last edited on
Oops! Sorry, totally missed that.

Thanks for pointing out.
@abhishekm71 Don't worry. It happens to all of us.
Topic archived. No new replies allowed.