Calculate factorial of the largest numbers - c++

i want to calculate the factorial of the numbers greater than 30 , when i want to calculate factorial the result is 0 .
#include <iostream>
using namespace std;
void fun1();
int main()
{
fun1();
}
void fun1(){
int x ;
int sum = 1 ;
cout << "Enter your number:";
cin >> x ;
if ( x >= 1 ){
for ( int i = x ; i > 1 ; i--){
sum *= i ;
}
}
cout << "Factorial of " << x << " is :" << sum ;
}

You can use larger data types (unsigned long long int if available).
You can cheat some digits off by checking whenever you have a 2 and 5 factors in the expression, removing them and remembering to output an extra 0 at the end:
6! = 6 * 5 * 4 * 3 * 2 = ( 6 * 4 * 3 ) * (5*2) = "72""0"
best of all you use a "large number" or "arbitrary precision" library

Related

While coding addition of two polynomials in c++ , I could compute the addition when no and order of terms are same . It shows error when its diff,why?

Here I have tried to code addition of two single variable polynomials in c++ . The code runs fine when both the inputs are in sync with the other . But when it ain't it shows some crazy stuff happening and prints complete gibberish . I am pasting my code here with the output . Any suggestions would be helpful .
My Code
#include <iostream>
using namespace std;
class Term
{
public :
int coeff;
int exp;
};
class Poly
{
private:
int n;
Term *terms;
public:
Poly(int n)
{
this->n = n;
terms = new Term[n];
}
void create();
void Display();
Poly* add(Poly &p2);
~Poly()
{
delete []terms;
}
};
void Poly::create()
{
cout << "Enter Terms " << endl;
for(int i = 0; i<n;i++)
{
cin >> terms[i].coeff >> terms[i].exp ;
}
}
void Poly::Display()
{
for(int i = 0;i<n;i++)
{
cout <<terms[i].coeff<<"x"<<terms[i].exp <<" + ";
}
}
Poly* Poly :: add(Poly &p2)
{
int i,j,k;
Poly* sum = new Poly(n+p2.n);
i = j = k = 0 ;
while(i<n && j<p2.n)
{
if(terms[i].exp>p2.terms[j].exp)
{
sum->terms[k++] = terms[i++];
}
else if(terms[i].exp<p2.terms[j].exp)
sum->terms[k++] = terms[j++];
else
sum->terms[k].exp = terms[i].exp;
sum->terms[k++].coeff = terms[i++].coeff +p2.terms[j++].coeff ;
}
for(;i<n;i++)
{
sum->terms[k++] = terms[i];
}
for(;j<p2.n;j++)
{
sum->terms[k++] = p2.terms[j];
}
sum->n = k;
return sum ;
}
int main()
{
int n,m;
cout << "Enter no.of terms for 1st Polynomial" << endl ;
cin >> n;
Poly p1(n);
p1.create();
cout << "Enter no.of terms for 2nd Polynomial" << endl ;
cin >> m ;
Poly p2(m) ;
p2.create();
Poly *p3 ;
p3 = p1.add(p2);
cout << endl;
p1.Display();
cout << endl;
cout << "-------" << endl ;
p2.Display();
cout << endl;
cout << " ------------" << endl ;
p3->Display();
return 0;
}
Output 1:(passing 1st test Case)
Enter no.of terms for 1st Polynomial
5
Enter Terms
2 5
3 4
6 3
7 2
8 1
Enter no.of terms for 2nd Polynomial
5
Enter Terms
3 5
8 4
1 3
5 2
6 1
2x5 + 3x4 + 6x3 + 7x2 + 8x1 +
-------
3x5 + 8x4 + 1x3 + 5x2 + 6x1 +
------------
5x5 + 11x4 + 7x3 + 12x2 + 14x1 +
Process returned 0 (0x0) execution time : 48.853 s
Press any key to continue.
Output II(Failing the Test Case 2)
Enter no.of terms for 1st Polynomial
5
Enter Terms
3 5
2 4
8 3
4 2
6 1
Enter no.of terms for 2nd Polynomial
4
Enter Terms
7 5
4 3
8 1
2 0
3x5 + 2x4 + 8x3 + 4x2 + 6x1 +
-------
7x5 + 4x3 + 8x1 + 2x0 +
------------
10x5 + 2x4 + 12x-1 + 4x2 + 14x0 + 2x0 +
Process returned 0 (0x0) execution time : 56.271 s
Press any key to continue.
Any help suggestions to solve the problem would be appreciated . Thank You .
The main mistake in your code is this line:
sum->terms[k++].coeff = terms[i++].coeff +p2.terms[j++].coeff ;
and, more precisely, its location in the whole routine.
Namely, it is located past the if - else if - else construct. As a result, it is executed despite exponents satisfy the 'less-than', the 'greater-than' or the 'equal' condition; and it should be done in the last case only.
The relevant part of code should be enclosed with another pair of curly braces:
while(i<n && j<p2.n)
{
if(terms[i].exp>p2.terms[j].exp)
sum->terms[k++] = terms[i++];
else if(terms[i].exp<p2.terms[j].exp)
sum->terms[k++] = terms[j++];
else
{
sum->terms[k].exp = terms[i].exp;
sum->terms[k++].coeff = terms[i++].coeff +p2.terms[j++].coeff ;
}
}
Another error is in the else if branch: you use the j index to the this->terms array:
sum->terms[k++] = terms[j++];
while you should use the p2.terms:
sum->terms[k++] = p2.terms[j++];

Why is the ILS_best_p not giving me the vector I want?

I would like to store the smallest value of compute_evaluation_function in current_best_eval, and the corresponding vector that gives that smallest value in ILS_best_p, I've succeeded with the current_best_eval, but can't seem to get it for the ILS_best_p even though they're under the same if statement.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cmath>
using namespace std;
long int **read_matrix(ifstream &input, long int n);
double ran01(long int *idum);
long int *generate_random_vector(long int n);
unsigned long int compute_evaluation_function(long int n);
void first_2_opt_symmetric (long int n);
void swap(long int pos_1, long int pos_2, long int *);
void perturbation(long int pert_size);
long int *p;//the vector generated from generate_random_vector()
long int **d;//one of the matrices read from file
long int **f;//one of the matrices read from file
long int n;
long int actual_solution_value;
long int new_eval;
long int current_eval;
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
int main()
{
string name;
long int optimum;
ifstream infile;
long int initial_eval;
long int *ILS_best_p;
long int new_vs_current;
new_vs_current = INT_MAX;
long int current_best_eval;
current_best_eval = INT_MAX;
long int new_current_eval;
long int best_eval;
long int improvement;
long int i;
long int j;
infile.open("nug12.dat");
infile >> name;
cout << "Name: " << name << "\n";
infile >> n;
cout << "Rows and Columns: " << n << "\n";
infile >> optimum;
cout << "Optimum solution: " << optimum << "\n";
d=read_matrix(infile, n);
f=read_matrix(infile, n);
cout << endl;
p=generate_random_vector(n);
compute_evaluation_function(n);
cout << endl;
first_2_opt_symmetric (n);
cout << endl;
initial_eval = compute_evaluation_function(n);
cout << endl << endl;
for (i = 0; i < 500; i++) //ILS loop
{
if (new_eval < current_eval)
{
new_vs_current = new_eval;
cout << "iteration 1st = " << i+1 << " " << endl;
}
else if (current_eval < new_eval)
{
new_vs_current = current_eval;
cout << "iteration 2nd = " << i+1 << " " << endl;
}
cout << "iteration = " << i+1 << " " << endl;
cout << " Vector before perturbation = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
perturbation(3);
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
cout << " Vector after perturbation = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
first_2_opt_symmetric (n);
new_current_eval = compute_evaluation_function(n);
cout << endl << "current best eval = " << current_best_eval << endl;
cout << endl;
cout << " Vector after local search = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
cout << " Vector p = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
if (new_current_eval < current_best_eval)
{
new_eval = new_current_eval;
cout << "iteration 3rd = " << i+1 << " " << endl;
}
else if (current_best_eval <= new_current_eval)
{
new_eval = current_best_eval;
cout << "iteration 4th = " << i+1 << " " << endl;
}
if (new_eval < new_vs_current)
{
current_best_eval = new_eval;
cout << "iteration 5th = " << i+1 << " " << endl;
ILS_best_p = p;
}
else if (new_vs_current < new_eval)
{
current_best_eval = new_vs_current;
cout << "iteration 6th = " << i+1 << " " << endl;
ILS_best_p = p;
}
cout << endl << "current best eval = " << current_best_eval << endl;
}
cout << endl << "current best eval = " << current_best_eval << endl;
cout << "ILS best vector = ";
for (i = 0; i < n; i++)
{
cout << ILS_best_p[i] << " ";
}
return 0;
}
long int **read_matrix(ifstream &input, long int n)
{
/*
FUNCTION: read instance matrices
INPUT: instance file name, instance size
OUTPUT: d-matrix and f-matrix
(SIDE)EFFECTS: none
COMMENTS: read the distance matrix and flow matrix
*/
long int i, j;
long int **matrix = new long int *[n];
for (i = 0; i < n; i++)
{
matrix[i] = new long int[n];
for (j = 0; j < n; j++)
{
if( !(input >> matrix[i][j]) )
{
cerr << "Error reading at " << i << j << endl;
exit(1);
}
}
}
return matrix;
}
double ran01(long int *idum)
{
/*
FUNCTION: returns a pseudo-random number
INPUT: a pointer to the seed variable
OUTPUT: a pseudo-random number uniformly distributed in [0,1]
(SIDE)EFFECTS: changes the value of seed
*/
long k;
double ans;
k =(*idum)/IQ;
*idum = IA * (*idum - k * IQ) - IR * k;
if (*idum < 0 )
{
*idum += IM;
}
ans = AM * (*idum);
return ans;
}
long int *generate_random_vector(long int n)
{
/*
FUNCTION: generates a random vector
INPUT: vector dimension
OUTPUT: returns pointer to vector, free memory when vector is not needed anymore
(SIDE)EFFECTS: none
*/
long int i, j, help;
long int *v;
srand(time(0));
long int seed=rand();
v = new long int[ n ];
for ( i = 0 ; i < n; i++ )
{
v[i] = i;
}
for ( i = 0 ; i < n-1 ; i++)
{
j = (long int) ( ran01( &seed ) * (n - i));
assert( i + j < n );
help = v[i];
v[i] = v[i+j];
v[i+j] = help;
}
return v;
}
unsigned long int compute_evaluation_function(long int n)
{
/*
FUNCTION: compute evaluation function
INPUT: pointer to solution
OUTPUT: evaluation function
(SIDE)EFFECTS: none
COMMENTS: none
*/
long int i, j;
unsigned long obj_f_value;
obj_f_value = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
obj_f_value += d[i][j] * f[p[i]][p[j]];
}
}
cout << obj_f_value;
return obj_f_value;
}
void first_2_opt_symmetric (long int n)
{
/*
FUNCTION: first improvement 2-opt local search for symmetric instances
INPUT: pointer to some initial assignment
OUTPUT: none
(SIDE)EFFECTS: initial assignment is locally optimized, dlb is used to increase the search speed, the dlb value is changed to false if item change it's location during perturbation
COMMENT: neighborhood is scanned in random order, use of register for faster computation
*/
long int improvement = 1;
long int improve_item = 0;
long int u, v, i, j, k;
long int tmp;
long int *x;
improvement = 1;
x = generate_random_vector(n);
while (improvement)
{
improvement = 0;
for ( i = 0 ; i < n ; i++ )
{
u = x[i];
improve_item = 0;
for ( j = 0 ; j < n ; j++ )
{
v = x[j];
if (u == v)
continue;
tmp = 0;
for ( k = 0 ; k < n ; k++ )
{
if ( (k != u) && (k != v) )
{
tmp += (d[u][k] - d[v][k]) * (f[p[v]][p[k]] - f[p[u]][p[k]]);
}
}
if (tmp < 0)
{
improvement = 1;
improve_item = 1;
swap (u, v, p);
}
}
}
}
delete []x;
}
void swap(long int pos_1, long int pos_2, long int *p)
{
/*
FUNCTION: swap position of two items in a vector
INPUT: position 1, position 2, pointer to vector
OUTPUT: none
(SIDE)EFFECTS: none
COMMENTS: none
*/
long int tmp;
tmp = p[pos_1];
p[pos_1] = p[pos_2];
p[pos_2] = tmp;
}
void perturbation(long int pert_size)
{
/*
FUNCTION: apply random perturbation
INPUT: pointer to solution, perturbation scheme, perturbation strength, change in perturbation, end perturbation size
OUTPUT: none
(SIDE)EFFECTS: new solution formed from old solution
COMMENTS: none
*/
long int hold_value[n]; //allocate memory for items to be chosen in move/*
int chosen[pert_size]; //*allocate temporary memory to determine items to be moved */*
long int i;
for(i = 0; i < n; i++)
{
hold_value[i] = p[i]; //initialize hold_value with the same value from local search/*
}
int j = n - 1;
int rand_number;
int rand_no;
for(i = 1; i <= pert_size; i++)
{
rand_number = rand();
rand_no = rand_number % j; //choose random number from 1 to size - 1/
chosen[i - 1] = rand_no + i; //copy the value to chosen[i]
j--;
}
long int temp;
for(i = 0; i < pert_size; i++)
{
temp = chosen[i];
swap(i, temp, hold_value); //swap chosen[i] and hold_value[i]; n first item in hold_value[i] is the index array that will be included in perturbation/
}
long int temp1;
long int temp2;
temp1 = p[hold_value[1]];//
temp2 = p[hold_value[0]];
for(i = 0; i < pert_size - 1; i++)
{
p[hold_value[i + 1]] = temp2;
temp2 = temp1;
temp1 = p[hold_value[i + 2]];
}
p[hold_value[0]] = temp2;
actual_solution_value = compute_evaluation_function(n);
new_eval = actual_solution_value;
current_eval = new_eval;
}
This is the file I read from:
Nug12
12
578
0 1 2 3 1 2 3 4 2 3 4 5
1 0 1 2 2 1 2 3 3 2 3 4
2 1 0 1 3 2 1 2 4 3 2 3
3 2 1 0 4 3 2 1 5 4 3 2
1 2 3 4 0 1 2 3 1 2 3 4
2 1 2 3 1 0 1 2 2 1 2 3
3 2 1 2 2 1 0 1 3 2 1 2
4 3 2 1 3 2 1 0 4 3 2 1
2 3 4 5 1 2 3 4 0 1 2 3
3 2 3 4 2 1 2 3 1 0 1 2
4 3 2 3 3 2 1 2 2 1 0 1
5 4 3 2 4 3 2 1 3 2 1 0
0 5 2 4 1 0 0 6 2 1 1 1
5 0 3 0 2 2 2 0 4 5 0 0
2 3 0 0 0 0 0 5 5 2 2 2
4 0 0 0 5 2 2 10 0 0 5 5
1 2 0 5 0 10 0 0 0 5 1 1
0 2 0 2 10 0 5 1 1 5 4 0
0 2 0 2 0 5 0 10 5 2 3 3
6 0 5 10 0 1 10 0 0 0 5 0
2 4 5 0 0 1 5 0 0 0 10 10
1 5 2 0 5 5 2 0 0 0 5 0
1 0 2 5 1 4 3 5 10 5 0 2
1 0 2 5 1 0 3 0 10 0 2 0

Program returning single value for double (C++)

Basically I just started doing C++ again after a while because I need to (Degree sorta commands it) and I have been tasked with a simple task of writing a simple program that would take a function and use 2 integer inputs (N and M), returning a double output (S). In one part I am asked to to use a loop to display values for S all the way up to N=10 from N=0 for the value M=10
Ive run into a problem where the return give the value "5" for every N up to 10.
This is the code: (do not mind the comments)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
//Function, Part A
double func_18710726(int N, int M)
{
double S = 0;
for (int n = 1; n <= N; n++)
for (int m = 1; m <= M; m++)
{
S = S + (sqrt(m*n)+exp(sqrt(m))+ exp(sqrt(n)))/(m*n + 2);
}
return S;
}
//Part B
double func_18710726(int, int);
using namespace std;
int main()
{
int N, M;
double S;
//Part B1
do {
cout << "Enter Value of N for N > 0 and an integer" << endl;
cin >> N;
} while (N <= 0);
do {
cout << "Enter value of M for M > 0 and an integer" << endl;
cin >> M;
} while(M <= 0);
//Part B2
S = func_18710726(N, M);
cout << "The Summation is ";
cout << fixed << setprecision(5) << S << endl;
//Part B3
ofstream output;
output.open("Doublesum.txt");
M = 1;
for (int n = 1; n <= 10; n++)
{
S = func_18710726(n, M);
cout << "The summation for N = " << n << " is ";
cout << fixed << setprecision(5) << 5 << endl;
output << fixed << setprecision(5) << 5 << endl;
}
output.close();
return 0;
}
The output gives me:
Enter Value of N for N > 0 and an integer
1
Enter value of M for M > 0 and an integer
2
The Summation is 4.20696
The summation for N = 1 is 5
The summation for N = 2 is 5
The summation for N = 3 is 5
The summation for N = 4 is 5
The summation for N = 5 is 5
The summation for N = 6 is 5
The summation for N = 7 is 5
The summation for N = 8 is 5
The summation for N = 9 is 5
The summation for N = 10 is 5
--------------------------------
Process exited after 2.971 seconds with return value 0
Press any key to continue . . .
Any help as to why this is happening is much appreciated.
The Question itself
I am sorry if I posted this in the wrong place, if I do, Mods please go easy on me :)
This line:
cout << fixed << setprecision(5) << 5 << endl;
has 5 (five) as its output - you want S (esss)
Probably S is not such a great name for a variable (neither is l)

Finding maxium factorial n what intiger allows! C++

Sorry for bad English.
So my problem is that i need to find all possible factorials starting from 1.
I need it to stop when Int have maximum memory used and print out maximum factorial value. My code is pretty simple, but i do not know how to get to stop loop when it reach maximum of Intiger values.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k,n=0;
unsigned int factorial = 1;
unsigned int factorial2=1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for(int s = 1; s<=uval; ++s) {
factorial2 *= s;
if( s < uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
}
return 0;
}
The problem is that the loop is going to calculate factorial to all UINT_MAX values, and most of the output will be 0 becouse memory is overloaded.
But it should stop before it goes bigger that UINT_MAX memory!
Hope you all understand my problem and will help me with this.
In a 32-bit signed integer, 12! is the largest possible.
You can check this by doing
if (INT_MAX / fact_so_far < n)
{
std::cout << "Max factorial " << n-1 << std::endl;
}
[This code STOPS when it reaches the "unable to calculate", because INT_MAX / fact_so_far will not multiply without overflow].
if (INT_MAX / fact_so_far >= n)
{
fact_so_far *= n;
}
else
{
std::cout << n << " is too large to calculate factorial" << std::endl;
}
would be the other way to do this. [Obviously with suitable loop to increment n]
Not that MAX_UINT is the max value for unsigned int, not for int [it's typically half that].
Edit to explain the logic:
The logic here is that if we divide INT_MAX with what our current factorial value is, it should produce a value larger than n [the current multiplier for the next factorial].
As a simple step through example, we pick a MAX_INT of 127:
Initial state:
factorial = 1, n = 1;
Steps:
n = 2, MAX_INT / factorial = 127 -> factorial *= n => 2
n = 3, MAX_INT / factorial = 63 -> factorial *= n => 6
n = 4, MAX_INT / factorial = 21 -> factorial *= n => 24
n = 5, MAX_INT / factorial = 5 -> factorial *= n = 120
n = 6, MAX_INT / factorial = 1 -> FAIL - will overflow.
Before calculating the next factorial in the list, see if the previous one is greater than UINT_MAX / i. If it is, you know that the next multiplication will go out of bounds.
If factorial2 > UINT_MAX / (s+1), the next factorial can't be calculated.
By the way, you should use unsigned int for factorial2
You are comparing the signed int with an unsigned one i.e. you are doing i < UINT_MAX (This is the maximum value of unsigned int) which is wrong and will result in overflow and wrong condition check.
so i finaly did this with my code. Now it works but its not realy good. Maybe someone someday will need something like this as a start for his own max factorial programm. First program will ask you to insert a random number and then it calculate its factorial (only in max int borders). Then it prints out all possible int factorials. Its show only 11! as max but the max is 12! I add factorial 12! manualy, becouse the if statment cannot print out excatly the number 12 as max it prints one before. And in the end the programm shows you what is maxium possible factorial for intiger.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k, max,s;
unsigned int factorial = 1;
unsigned int factorial2 = 1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for( s = 1; s<=uval; ++s) {
factorial2 *= s;
max=factorial2;
if( s <= uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
else {
break;
}
}
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
cout <<" \nMaksimalais faktorials ir skaitla " << s << " faktorials ==> " <<max;
return 0;
}
This is what the programm looks like!
![Programm][1]

Recursion final number

If my input number is 2...I understand that the function will take the previous answer and multiply by 2 until the number will be greater than 25
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
16 * 2 = 32...program stops since num is 32
but then my final number is 62 how am I getting that number>
#include <iostream>
using namespace std;
int myRecursiveFunction (int num)
{
if (num >= 25) // stopping condition
return num;
else
cout << "number is at " << num << endl;
return num = num + myRecursiveFunction (num * 2);
}
int main()
{
int num, num1;
cout << "Enter a number: ";
cin >> num;
num1 = myRecursiveFunction(num);
cout << "Final number is: " << num1;
return 0;
}
You want to do this:
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
16 * 2 = 32...program stops since num is 32
you are doing
return num = num + myRecursiveFunction (num * 2);
which returns 32+16+8+4+2 = 62
2 + 4 + 8 + 16 + 32 = 62.
The return values are getting added each time.