TheAlgorithms-C-Plus-Plus/math/power_for_huge_numbers.cpp

92 lines
1.6 KiB
C++
Raw Normal View History

2019-02-13 21:58:19 +08:00
#include <iostream>
using namespace std;
2019-02-13 21:58:19 +08:00
// Maximum number of digits in output
// x^n where 1 <= x, n <= 10000 and overflow may happen
2019-02-13 21:58:19 +08:00
#define MAX 100000
2019-02-13 21:58:19 +08:00
// This function multiplies x
// with the number represented by res[].
// res_size is size of res[] or
// number of digits in the number
// represented by res[]. This function
// uses simple school mathematics
// for multiplication.
// This function may value of res_size
// and returns the new value of res_size
2019-08-21 10:10:08 +08:00
int multiply(int x, int res[], int res_size)
{
2019-02-13 21:58:19 +08:00
// Initialize carry
int carry = 0;
2019-02-13 21:58:19 +08:00
// One by one multiply n with
// individual digits of res[]
2019-08-21 10:10:08 +08:00
for (int i = 0; i < res_size; i++)
{
2019-02-13 21:58:19 +08:00
int prod = res[i] * x + carry;
2019-02-13 21:58:19 +08:00
// Store last digit of
// 'prod' in res[]
res[i] = prod % 10;
2019-02-13 21:58:19 +08:00
// Put rest in carry
carry = prod / 10;
}
2019-02-13 21:58:19 +08:00
// Put carry in res and
// increase result size
2019-08-21 10:10:08 +08:00
while (carry)
{
2019-02-13 21:58:19 +08:00
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
2019-02-13 21:58:19 +08:00
// This function finds
// power of a number x
void power(int x, int n)
{
2019-02-13 21:58:19 +08:00
//printing value "1" for power = 0
2019-08-21 10:10:08 +08:00
if (n == 0)
{
cout << "1";
2019-02-13 21:58:19 +08:00
return;
}
2019-02-13 21:58:19 +08:00
int res[MAX];
int res_size = 0;
int temp = x;
2019-02-13 21:58:19 +08:00
// Initialize result
2019-08-21 10:10:08 +08:00
while (temp != 0)
{
2019-02-13 21:58:19 +08:00
res[res_size++] = temp % 10;
temp = temp / 10;
}
2019-02-13 21:58:19 +08:00
// Multiply x n times
// (x^n = x*x*x....n times)
for (int i = 2; i <= n; i++)
res_size = multiply(x, res, res_size);
2019-02-13 21:58:19 +08:00
cout << x << "^" << n << " = ";
for (int i = res_size - 1; i >= 0; i--)
cout << res[i];
}
2019-02-13 21:58:19 +08:00
// Driver program
2019-08-21 10:10:08 +08:00
int main()
{
2019-02-13 21:58:19 +08:00
int exponent, base;
printf("Enter base ");
scanf("%id \n", &base);
printf("Enter exponent ");
scanf("%id", &exponent);
power(base, exponent);
return 0;
}