Binary Exponentiation in C++ - c++

Find below my implementation for binary exponentiation
#include<iostream>
#include<cmath>
using namespace std;
int fast_exponentiation(int base, int pow) {
unsigned int result; // variable to store intermediaries
if (pow == 1) {
return base;
}
else if (pow == 0) {
return 1;
}
result = fast_exponentiation(base, floor(pow/2));
// even power
if (pow % 2 == 0) {
return result * result;
}
// odd power
else {
return result * base * result;
}
}
int main() {
int num, answer, p;
cout << "Enter the base: ";
cin >> num;
cout << "Enter power: ";
cin >> p;
answer = fast_exponentiation(num, p);
cout << answer << endl;
return 0;
}
The problem is when I ran this for inputs num= 3 and pow = 20 I get -808182895, a negative number. I can't seem to figure out what is wrong with the code? Can I get some help?

Value of 3^20 exceeds max possible int value 2^31, so you have got overflow. The simplest way to overcome this limit is using long long data type to provide possiblity for calculations upto power 39 (near 2^63)
For larger powers one need long number arithmetics - boost multi-precision, GMP etc

Related

How to find the factorial of 100 in C++?

I am writing a program to calculate the factorial of 100. The code is as below. Notwithstanding, the output is 0 as the answer is too big. Is there any answer to display the exact answer? This is because even unsigned long long is not even able to display the factorial of 100. Thank you.
#include <iostream>
using namespace std;
int main()
{
int n,i,fact=1;
cout << "enter the number "<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<"the factorial is "<<fact<<endl;
}
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 22!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
You can use C++ Boost Library to to manipulate such large numbers.
Here is the code:
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using namespace boost::multiprecision;
cpp_int fact(int);
int main(){
cpp_int a=1;
int n;
cin>>n;
cout<<fact(n)<<endl;
}
cpp_int fact(int x){
if(x==1)
return 1;
cpp_int temp=1;
temp= x*fact(x-1);
return temp;
}

C++: about precision of calculating (code is inside)

Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)

int limit in permutation program (C++)

I wrote a simple C++ program that computes permutations/factorials in 2 different methods. The problem arises when I try to use the longer method (p1) with 20 and 2. Granted, "20!" is a HUGE number. Is there a limit with integers when calculating the factorial using the recursion method?
#include <iostream>
using namespace std;
int p1(int n, int r);
int p2(int n, int r);
int factorial(int x);
int main()
{
cout << p1(10, 8) << endl;
cout << p2(10, 8) << endl;
cout << p1(4, 3) << endl;
cout << p2(4, 3) << endl;
cout << p1(20, 2) << endl; // THE NUMBER PRINTS INCORRECTLY HERE
cout << p2(20, 2) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
int p1(int n, int r) // long version, recursively calls factorial
{
return (factorial(n) / factorial(n - r));
}
int factorial(int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
int p2(int n, int r) // shortcut, does arithmetic in for loop
{
int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
20! is 2.4*10^18
You can check out a reference of limits.h to see what the limits are.
consider that 2^32 is 4.2*10^9. long int is usually a 32-bit value.
consider that 2^64 is 1.8*10^19, so a 64-bit integer will get you through 20! but no more. unsigned long long int should do it for you then.
unsigned long long int p1(int n, int r)
{
return (factorial(n) / factorial(n - r));
}
unsigned long long int factorial(unsigned long long int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
unsigned long long int p2(int n, int r)
{
unsigned long long int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
If you are allowed in this assignment, consider using float or double, unless you need absolute precision, or just need to get to 20 and be done. If you do need absolute precision and to perform a factorial above 20, you will have to devise a way to store a larger integer in a byte array like #z32a7ul states.
Also you can save an operation by doing answer *= --n; to pre-decrement n before you use it.
20! exceeds the integer range. Your shortcut function doesn't exceed simply because you don't calculate the whole faculty, but 20*19
If you really need it, you may create a class that holds a variable-length array of bytes, and define operators on it. In that case, only the available memory and your patiance will limit the size of numbers. I think Scheme (a LISP dialect) does something like that.

Binary To Decimal Recursion - without global variable

i am learning recursion in C++ and as practice i was trying to write binary to decimal converter with recursive function. In following code converter is working as it should:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int sum = 0;
int DecimalConversion (int power, int number){
int bit;
if (number == 0)
{
return 0;
}
bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
DecimalConversion(power, number);
return sum;
//return bit * pow(2, power) + DecimalConversion(power, number);
}
int main(){
int power = 0;
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(power, number);
system("PAUSE >> NULL");
return 0;
}
Is it possible to return value from DecimalCoonversion function by not using global variable? Can someone explain how, I tried next line of code but it does not work correctly:
return bit * pow(2, power) + DecimalConversion(power, number);
Can anyone explain where i am making mistake using previous line of code?
Thank You in advance
This adds sum as a parameter to your function, but makes it default to 0 if you don't provide it explictly. Power is also defaulted to 0, which saves you having to pass it into the function.
Since default parameters must be at the end of a function declarations and/or definitions parameter list, I had to move power across to achieve this.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int DecimalConversion (int number, int power = 0, int sum = 0) // changes here
{
if (number == 0)
{
return sum;
}
int bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
return DecimalConversion(number, power, sum); // changes here
}
int main(){
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(number);
system("PAUSE >> NULL");
return 0;
}
Please note I didn't check this actually converts binary to decimal correctly, just that the recursion works.
You can call this function like so:
DecimalConversion(number);
This:
int DecimalConversion(int power, int number){
if (number == 0)
return 0;
else
return (number % 10)*pow(2, power) + dc(power+1, number/10);
}
or
int DecimalConversion(int power, int number){
return number?(number % 10)*pow(2, power) + dc(power+1, number/10):0;
}

automatic rounding off a during typecasting in c++

I did something like this
long double n;
cin >> n;
n = n * 10000;
long long int temp = (long long) n;
now when i try to print temp, then a problem occours in some test cases like 2.36
for 2.36 the value of temp should be 23600 but the value of temp comes out to be 23599
Pls someone help me out with this already got 4 wrong ans for this.. small problem
for simplification ..
my code goes like this
int main()
{
int t;
for(scanf("%d", &t); t-- ;) {
float n;
scanf("%f", &n);
n *= 10000;
long int as = (long int) n;
cout << "\nas : " << as << " n : " << n << endl;
long a, b;
a = as;
b = 10000;
while(a%b != 0) {
long temp = a % b;
a = b;
b = temp;
}
long factor = b;
cout << (10000/factor) << endl;
}
return 0;
}
the aim of this program was something that .. i was given a number that can have at max 4 places after the decimal. that was the average score scored by a batsman so we had to find the minimum number of matches he should play to get that score
This is because of the way floating-points are represented internally. You should round them off before performing truncation.
Doing a floor(n+0.5) or a ceil(x-0.5) would round the number correctly.
EDIT:
As your truncation step is a floor(..) operation in itself, you should just do n = n * 10000 + 0.5 as #Mooing Duck stated.
(Example)