Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a square() function without x*x in C++

Tags:

c++

I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:

Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a variable result at 0 and add x to it x times). Then run some version of “the first program” using that square().

Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:

int square(int x)
{
    int i = 0;
    for(int counter = 0; counter < x; ++counter)
    {
        i = i + x;
    }

return i;
}

But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?

like image 695
jiggumbob Avatar asked Mar 23 '16 03:03

jiggumbob


People also ask

How do I square a number in CPP?

When we square a number, we simply multiply it by itself. We have to utilize a header file if we want to get a square of a number. Header files allow us to declare a function with a type placeholder that the compiler will fill in at compile-time based on how the function is used.


2 Answers

int square(int x) {
    int result = { 0 };
    int *ptr = &result;
    for (int i = 0; i < x; i++) {
        *ptr = *ptr + x;
    }
    return *ptr;
}

I am reading that book atm. Here is my solution.

like image 94
icer Avatar answered Oct 13 '22 02:10

icer


Mats Petersson stole the idea out of my head even before I thought to think it.

#include <iostream>

template <typename T>
T square(T x) {
    if(x < 0) x = T(0)-x;
    T sum{0}, s{x};
    while(s) {
        if(s & 1) sum += x;
        x <<= 1;
        s >>= 1;
    }
    return sum;
}

int main() {
    auto sq = square(80);
    std::cout << sq << "\n";
}
like image 42
2 revs Avatar answered Oct 13 '22 02:10

2 revs