0
How to find the power of a number with only addition and loops?
There is a question in my assessment to write a program that takes 2 numbers from the user n1 and n2 and finds n1 to the power n2 (n1^n2). I am not allowed to use the math library or simple multiplication. All I can use is simple addition and loops. I tried a lot but can't get the program right. Please help.
7 Respostas
+ 9
You can also use the Web version of SoloLearn.
+ 8
Welcome 😊
+ 7
Like others said, if you are having trouble with your code, post a link to your code so that you can get helpful answers and others can identify your mistakes which will help you more in learning rather than asking for a code. :)
#include <iostream>
using namespace std;
int Multiplication(int num, int sum);
int main()
{
int num = 0, pow = 0, sum = 0;
cin >> num;
cin >> pow;
cout << "You entered " << num << "^" << pow << endl;
for(int i = 0; i < pow - 1; i++)
{
sum = Multiplication(num, sum);
}
cout << num << "^" << pow << " = " << sum << endl;
return 0;
}
int Multiplication(int num, int sum)
{
int temp = (sum == 0)? num : sum;
sum = 0;
for(int i = 0; i < num; i++)
sum += temp;
return sum;
}
+ 2
Show your attempt to receive some helpful answers.
+ 1
You could begin by making your own multiplication function.
Multiplying a number x by y means nothing more than adding x to itself y - 1 times. This is something you can achieve using addition and a for-loop.
Using this function and the same pattern you can afterwards design your power function. Again, raising a number x to y means multiplying x by itself y - 1 times. Here you can use a for-loop again.
For more detailed help, you should provide us with your own attempt just as Mohit suggested so we can see what you are trying to do.
+ 1
Thanks alot nAutAxh AhmAd. I code on my laptop so that's why I couldn't post my code.
0
Okay I'll give it a try. Thanks for your help☺