How to find the factorial of 100 in C++? - 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;
}

Related

c++ conversion from decimal to binary

i am writing program for conversion of decimal to binary but answer i am getting is not correct i had checked it multiple times but couldn't make it.
`
#include<iostream>
#include<math.h>
using namespace std;
int decitobin(int n){
int ans=0;
int i=0;
while(n!=0){
int bit=n&1;
ans=((bit * pow(10,i))+ans);
n=n>>1;
i++;
}
return ans;
}
int main(){
int n;
cin>>n;
if(n<0){
n=n*(-1);
int newans=decitobin(n);
//1stcomp
newans=(~newans);
newans=newans+1;
cout<<newans<<endl;
}
else{
cout<<decitobin(n);
}
}
`
i am getting output
100 for 5,99 for 4
and -109 for -6
i had checked each line make it match with the solution but could not figure it out
Note in C++ there is an easier way (though that probably will not be what your teacher asked for)
#include <bitset>
#include <iostream>
int main()
{
std::size_t value{ 112ul };
std::bitset<8> bits{ value };
std::cout << bits;
return 0;
}
Another way of doing it in code without even needing base 10 logic.
Just to show you numbers in memory are already in binary format.
Often in dealing with binary data you will need masks and shift operations.
#include <array>
#include <iostream>
auto get_number_of_bits(int value)
{
std::size_t n{ 1ul };
value >>= 1;
while (value != 0)
{
++n;
value >>= 1;
}
return n;
}
// note value will already be a binary number in memory
// we just need to "walk" over all the bits and
// insert a '0' or '1' to the string
std::string to_bin(const int value)
{
// calculate the number of bits present in the number
const auto number_of_bits{ get_number_of_bits(value) };
// allocate a string to hold the correct/minimal number of bits in the output
std::string string(number_of_bits,0);
int mask{ 0x01 << (number_of_bits - 1ul) }; // select which bit we want from number
// loop over the bits
for (std::size_t n{ 0ul }; n < number_of_bits; ++n)
{
string[n] = (value & mask) ? '1' : '0'; // test if bit is set if so insert a 1 otherwise a 0
mask >>= 1;
}
return string;
}
int main()
{
std::cout << to_bin(5) << "\n";
std::cout << to_bin(12345) << "\n";
return 0;
}

Binary Exponentiation in 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

Overflow in C++

So..
Here is the code:
#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
int main()
{
unsigned long long i,y,n,x=45;
unsigned long long factorial = 1;
for(n = 0; n <= 5; n++)
{
y = (pow(-1,n)*pow(x,2*n)) / factorial;
cout << "COS IS " << y << endl;
}
for(int i = 1; i <=n; i++)
{
factorial *= 2*i;
}
}
I get an overflow but I really don't know why. I use unsigned long long just to make sure that I on't get but.. I still get it. Even limited to small numbers. I tried to implement this:
https://en.wikibooks.org/wiki/Trigonometry/Power_Series_for_Cosine_and_Sine
But I really can't do it because of the overflow. Do you have any ideea on what can I do ? I am newbie in programming so, take it easy on me :D
There are many issues.
you use integer types when you should use floating point types
you use unsigned types for signed calculations
you don't use radians but degrees (45° ≈ 0.78539 radians)
you don't calculate the factorial in the loop, it is always 1, you only calculate it at the end of the loop but then it's too late, and your calculation of the factorial is wrong anyway.
the algorithm is wrong, it just doesn't do what Maclaurin's therorem says, you need to sum up the terms, but you just print the terms.
You probably want this:
#include <iostream>
#include <cmath>
using namespace std;
long factorial(int n)
{
long result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
int main()
{
double x = 0.785398163397448309616; //PI/4 expectd result COS(PI/4) = 0.7071067
double mycosinus = 0;
for (int n = 0; n <= 5; n++)
{
mycosinus += (pow(-1, n) * pow(x, 2 * n)) / factorial(2*n);
cout << "COS IS " << mycosinus << endl;
}
}
This is your wrong algorithm for calculating the factorial of 5:
int main()
{
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= 2 * i;
}
cout << "factorial 5 = " << factorial << endl;
}
The calculated value is 3840 instead of 120. I let you find out what's wrong yourself.
For performing this sort of maths you need to use a floating point like float or double not integral types like long, int or long long, given that sin and cos can both return negative numbers you shouldn't be using unsigned either.

C++ - how to find the length of an integer

I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).
Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.
I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!
Not necessarily the most efficient, but one of the shortest and most readable using C++:
std::to_string(num).length()
The number of digits of an integer n in any base is trivially obtained by dividing until you're done:
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base;
} while (n);
There is a much better way to do it
#include<cmath>
...
int size = trunc(log10(num)) + 1
....
works for int and decimal
If you can use C libraries then one method would be to use sprintf, e.g.
#include <cstdio>
char s[32];
int len = sprintf(s, "%d", i);
"I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
Closed formula for the longest int (I used int here, but works for any signed integral type):
1 + (int) ceil((8*sizeof(int)-1) * log10(2))
Explanation:
sizeof(int) // number bytes in int
8*sizeof(int) // number of binary digits (bits)
8*sizeof(int)-1 // discount one bit for the negatives
(8*sizeof(int)-1) * log10(2) // convert to decimal, because:
// 1 bit == log10(2) decimal digits
(int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign
For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".
If you want the number of decimal digits of some int value, you can use the following function:
unsigned base10_size(int value)
{
if(value == 0) {
return 1u;
}
unsigned ret;
double dval;
if(value > 0) {
ret = 0;
dval = value;
} else {
// Make room for the minus sign, and proceed as if positive.
ret = 1;
dval = -double(value);
}
ret += ceil(log10(dval+1.0));
return ret;
}
I tested this function for the whole range of int in g++ 9.3.0 for x86-64.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
Being a computer nerd and not a maths nerd I'd do:
char buffer[64];
int len = sprintf(buffer, "%d", theNum);
Would this be an efficient approach? Converting to a string and finding the length property?
int num = 123
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length
How about (works also for 0 and negatives):
int digits( int x ) {
return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}
Best way is to find using log, it works always
int len = ceil(log10(num))+1;
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
There are no inbuilt functions in C/C++ nor in STL for finding length of integer but there are few ways by which it can found
Here is a sample C++ code to find the length of an integer, it can be written in a function for reuse.
#include<iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
while(n>0)
{
integer_length++;
n = n/10;
}
cout<<integer_length<<endl;
return 0;
}
Here is another way, convert the integer to string and find the length, it accomplishes same with a single line:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
// convert to string
integer_length = to_string(n).length();
cout<<integer_length<<endl;
return 0;
}
Note: Do include the cstring header file
The easiest way to use without any libraries in c++ is
#include <iostream>
using namespace std;
int main()
{
int num, length = 0;
cin >> num;
while(num){
num /= 10;
length++;
}
cout << length;
}
You can also use this function:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
#include <math.h>
int intLen(int num)
{
if (num == 0 || num == 1)
return 1;
else if(num < 0)
return ceil(log10(num * -1))+1;
else
return ceil(log10(num));
}
Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.
#include <iostream>
using namespace std;
int main()
{
int n,len= 0;
cin>>n;
while(n!=0)
{
len++;
n=n/10;
}
cout<<len<<endl;
return 0;
}

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;
}