Reputation: 67
I'm trying to calculate the power of a number x^n, by just using pure addition like this: 2^4= 2+2+2+2+2+2+2+2 =16 so im using the following code to calculate 2^n:
add = x
for ( i = 1; i <= n-1; i++){
add = add + add;
}
cout<< x << "^" << n << " = " << add << endl;
so if you want to calculate 3^4 you have to put add = add + add + add
so my question is how do I make it work with any number that the user wants?
Upvotes: 1
Views: 742
Reputation: 61
// first deal with pow = 1 or 0 cases not shown here
// pseudocode for pow >= 2
var = 0
for (i = 0; i < num^(pow - 2); i++) // ^ is raising to power, not xor
for (j = 0; j < num; j++)
var += num
As you can see with the "i" condition check you have to use the power function anyway so not really possible with pure addition
Upvotes: 0
Reputation: 8647
For base b to the x <=> b^x
in C and with STRICTLY addition
int sum = b;
int add = b;
for (int i = 0; i < n+(-1); ++i) {
add = sum;
for (int j = 0; j < b+(-1); ++j) {
sum += add;
}
}
Upvotes: 3