I must implement a problem that computes combinations and multisets of m elements from a set of n elements.
The formulas for them are the following ones:
The problem is that with factorial it is easy to overflow, so basically what solutions can be for this problem?
Since it is a subproblem of a problem in TopCoder, I have following constraints:
1) A program must be written in C++.
2) I cannot load external libraries.
You don't really need to calculate n! directly, which may easily get overflowed. Since
C(n,m) = C(n-1, m-1) + C(n-1,m)
C(n,0) = C(n,n) =1
You can build a table with size (n+1,m+1) and use dynamic programming to build up the table in bottom up manner.
Algorithm pseudocode may like the following:
for i ← 0 to n do // fill out the table row wise
for j = 0 to min(i, m) do
if j==0 or j==i then C[i, j] ← 1
else C[i, j] ← C[i-1, j-1] + C[i-1, j]
return C[n, m]
If you declare c(n,m) to be long double and n is not that big, this way should work. Otherwise, you need to define your own BigInteger class to avoid overflow and define how the + operator works for BigIntegers, which are usually represented as array of chars or string.
Factorials are quite big numbers (they don't fit into a 64 bits word). So you need to use bignums (arbitrary precision arithmetic) to compute them in full. Consider using GMPlib for that purpose (or code in a language and implementation, e.g. Common Lisp with SBCL, which gives them natively)
See also this and that answers to a question very similar to yours.
Instead of using a recursive approach for calculating factorials which might lead to stack overflow, use iterative approach! This could save you overflow even for larger numbers.
Related
I need to print the number of coprime pairs (a,b), 0 < a <= b <= n and for n = 10^8 the program should run in less than 10 seconds. I have used this method : http://mathworld.wolfram.com/CarefreeCouple.html
But the program isn't as fast as I expected.
I have heard about an effient way of solving this problem by using something called 'Farey Sequence' but the code was written in PHP and I can only understand C.
So which method can help me solve the problem? thanks for the time.
Your stated interest is in co-prime pairs (a, b). The carefree couple adds an additional restriction that a is square-free. Therefore it is not the same problem, though some of the math is similar. As I understand your problem it is equivalent to summing the Euler totient function from 1 to n, the so-called Totient Summatory Function.
I do not know of any tricks that give one a simple closed form solution to come up with the answer. However, I think modifying a straightforward Sieve of Eratosthenes (SoT) should get you an answer in much less than 10 seconds in most programming languages.
Normally running the SoT simply yields a list of the primes <= n. Our goal will change, however, to computing the complete prime-power factorization of each integer between 1 and n inclusive. To do that we must store more than a single bit of information for each sieve entry, we must store a list. As we sieve a prime p through the array, we add (p, 1) to the list already stored at that entry. Then we sieve by p2 and change the (p,1) entries in each location we hit to (p,2), and so one for each power of p <= n and every p <= n. When it finishes, you
can compute the Totient function quickly for every value 0 <= x <= n and sum them up.
EDIT:
I see that there is already a much better set of answers to the question on math.stackexchange.com here. I'll leave this answer up for awhile until the disposition of the question is settled.
i want binary number that only have 0's at the beginning or end, for instance,
1111111
01111110
001111111
000111000
but no:
01001
0011101
do they have an specific name or property to get them?
I'm looking for something like linear integer optimization conditions, my solutions must have this form, but i can't think of any condition i can add to ensure that
Regards,
This is something which is not nice to formulate within mixed-integer programs. Most problems involving this are more suitable for alternative methods (SAT-solving, SMT-solving, Constraint-programming).
It can be done of course, but the solver will have some work as the formulation is non-trivial and introduces a lot of binary-variables (and the basic approach of MIP-solvers won't work amazingly here; bad integrality-gap).
I won't give you a complete solution, but some basic idea on how to formulate this and i also indicate how hard and cumbersome it is (there are alternative formulations; actually infinite many; but nothing much more simple).
The basic idea here is the following:
your binary number is constructed from N binary-variables
let's call them x
you introduce N auxiliary binary-variables l (left)
l[i] == 1 implicates: every l[j] with i<j is 0
you introduce N auxiliary binary-variables r (right)
r[i] == 1 implicates: every r[j] with i>j is 0
you add the following constraint for each position k:
x[k] == 0 implicates: l[i] == 1 for i < k OR r[i] == 1 for i>k
idea::
if there is a zero somewhere, either all on the left-side or all on the right-side are zeroes (or means: at least one side; but can be both)
To formulate this, you need two more ideas:
A: How to formulate the equality-check?
B: How to formulate the implication?
Remark: a -> b == not a or b (propositional calculus)
(this was wrongly stated earlier and corrected by OP)
These are common in MIP and you will find the solution in many integer-programming books, tutorial and papers. Here is an example (start with indicator-variables).
Another small common formulation:
if a is binary, b is binary:
a OR b is equivalent to: a+b >= 1 (the latter is a linear-expression ready to use for MIP)
Remark: The formulas in my idea-setting above might be wrong in regards to indices (i vs. i-1, vs. i+1) and binary-relations (<vs. <=). You will need to do the actual math yourself and just learn from the idea itself!
Remark 2: This kind of constraint is cumbersome in MIP, but more easily formulated within SAT and CP.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the efficient way to find factorial of a number other than normal recursive function and loop method? Since the normal method takes too longer to produce output is there any way to reduce the time complexity than the recursive and loop methods?If not why?
Since 79! is 1.711E98 you only need a list of 79 numbers to just use a lookup table.
The factorials are listed at: http://www.tsm-resources.com/alists/fact.html in integer format or at http://home.ccil.org/~remlaps/javascript/jstest1.html in scientific format, so it is just "cut and paste"
If you want to calculate many factorial values, then caching the values as you go along is an option.
If you just one a single calculation of factorial(n), then loop is probably the best you can get. You could possibly get more out of the processor by a bit of loop unrolling (calculating two or four multiplications at once), but it's unlikely to work for very large factorials, since multiplication in itself becomes a lengthy series of instructions.
As far as I'm aware, there is no "magical" math to calculate a sequence of 12 * 13 * 14 * 15 or similar faster than multiplying them together.
You may use Stirling's approximation to evaluate a large factorial.
Since one of your comments says you want to find 100000!, this answer covers huge factorials.
If you do not need an exact answer you can use Stirling's Approximation
If you want an exact answer you need to use an arbitrary precision math package like GMP
arbitrary precision math package
No, not really. If you are concerned with the run-time cost, it can be reduced with a look-up table (which requires that you use pre-calculated values).
To store every factorial may require too much memory, so lets store every k:th factorial.
This will require the program to perform up to k multiplications in runtime.
Let's say your runtime performance requirement limits you to 1000 multiplications for each factorial. Then you need to pre-calculate and store 1000!, 2000!, 3000! and so on up to the upper limit you want to support (available memory will limit you).
Since factorials quickly become larger than the native data types you need a class that can handle large numbers. I have assumed that ther exists such a class and that it is called BigInteger.
BigInteger preCalculatedValues[] = { new BigInteger("1"), new BigInteger("<value of 1000!>"), and so on... }
BigInteger factorial(int n) {
int pre = n/1000;
int i;
if (pre > LARGEST_VALUE_HANDLED) {
// Either throw an exception or let it take longer. I choose to let it take longer.
pre = LARGEST_VALUE_HANDLED;
}
BigInteger result = preCalculatedValues[pre];
for (i = pre * 1000 + 1; i <= n; i++) {
result.multiplyWith(i); // This operation is probably overloaded on the * operator
}
}
The simplest way of calculating very large factorals is to use
the gamma function. On the other hand: it won't be as fast as
the table lookup (as proposed by others); if you're using built
in types, you'll need tables of:
for 32 bits: 12 entries
for 64 bits: 20 entries
for float: 34 entries
for double: 170 entries
(There may be an off by one error in the above tables. I wrote
the code to calculate them very quickly.)
For double, and possibly for float, the usual loop method
will probably introduce too many rounding errors anyway. If you
don't want to use a table, and you have C++11,
exp( lgamma( i + 1 ) ) should do the trick. (If you don't
have C++11, you might have the lgamma function anyway. It's
in C99.)
If you're dealing with some sort of extended range type, you
might have to implement lgamma (and exp) for your type.
I'm having a trouble with my math:
Assume that we have a function: F(x,y) = P; And my question is: what would be the most efficient way of counting up suitable (x,y) plots for this function ? It means that I don't need the coordinates themself, but I need a number of them. P is in a range: [0 ; 10^14]. "x" and "y" are integers. Is it solved using bruteforce or there are some advanced tricks(math / programming language(C,C++)) to solve this fast enough ?
To be more concrete, the function is: x*y - ((x+y)/2) + 1.
x*y - ((x+y)/2) + 1 == P is equivalent to (2x-1)(2y-1) == (4P-3).
So, you're basically looking for the number of factorizations of 4P-3. How to factor a number in C or C++ is probably a different question, but each factorization yields a solution to the original equation. [Edit: in fact two solutions, since if A*B == C then of course (-A)*(-B) == C also].
As far as the programming languages C and C++ are concerned, just make sure you use a type that's big enough to contain 4 * 10^14. int won't do, so try long long.
You have a two-parameter function and want to solve it for a given constant.
This is a pretty big field in mathematics, and there are probably dozens of algorithms of solving your equation. One key idea that many use is the fact that if you find a point where F<P and then a point F>P, then somewhere between these two points, F must equal P.
One of the most basic algorithms for finding a root (or zero, which you of course can convert to by taking F'=F-P) is Newton's method. I suggest you start with that and read your way up to more advanced algorithms. This is a farily large field of study, so happy reading!
Wikipedia has a list of root-finding algorithms that you can use as a starting place.
I understand this is a classic programming problem and therefore I want to be clear I'm not looking for code as a solution, but would appreciate a push in the right direction. I'm learning C++ and as part of the learning process I'm attempting some programming problems. I'm attempting to write a program which deals with numbers up to factorial of 1billion. Obviously these are going to be enormous numbers and way too big to be dealing with using normal arithmetic operations. Any indication as to what direction I should go in trying to solve this type of problem would be appreciated.
I'd rather try to solve this without using additional libraries if possible
Thanks
PS - the problem is here http://www.codechef.com/problems/FCTRL
Here's the method I used to solve the problem, this was achieved by reading the comments below:
Solution -- The number 5 is a prime factor of any number ending in zero. Therefore, dividing the factorial number by 5, recursively, and adding the quotients, you get the number of trailing zeros in the factorial result
E.G. - Number of trailing zeros in 126! = 31
126/5 = 25 remainder 1
25/5 = 5 remainder 0
5/5 = 1 remainder 0
25 + 5 + 1 = 31
This works for any value, just keep dividing until the quotient is less
than 5
Skimmed this question, not sure if I really got it right but here's a deductive guess:
First question - how do you get a zero on the end of the number? By multiplying by 10.
How do you multiply by 10? either by multiplying by either a 10 or by 2 x 5...
So, for X! how many 10s and 2x5s do you have...?
(luckily 2 & 5 are prime numbers)
edit: Here's another hint - I don't think you need to do any multiplication. Let me know if you need another hint.
Hint: you may not need to calculate N! in order to find the number of zeros at the end of N!
To solve this question, as Chris Johnson said you have to look at number of 0's.
The factors of 10 will be 1,2,5,10 itself. So, you can go through each of the numbers of N! and write them in terms of 2^x * 5^y * 10^z. Discard other factors of the numbers.
Now the answer will be greaterof(x,y)+z.
One interesting thing I learn from this question is, its always better to store factorial of a number in terms of prime factors for easy comparisons.
To actually x^y, there is an easy method used in RSA algorithm, which don't remember. I will try to update the post if I find one.
This isn't a good answer to your question as you've modified it a bit from what I originally read. But I will leave it here anyway to demonstrate the impracticality of actually trying to do the calculations by main brute force.
One billion factorial is going to be out of reach of any bignum library. Such numbers will require more space to represent than almost anybody has in RAM. You are going to have to start paging the numbers in from storage as you work on them. There are ways to do this. The guy who recently calculated π out to 2700 billion places used such a library
Do not use the naive method. If you need to calculate the factorial, use a fast algorithm: http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
I think that you should come up with a way to solve the problem in pseudo code before you begin to think about C++ or any other language for that matter. The nature of the question as some have pointed out is more of an algorithm problem than a C++ problem. Those who suggest searching for some obscure library are pointing you in the direction of a slippery slope, because learning to program is learning how to think, right? Find a good algorithm analysis text and it will serve you well. In our department we teach from the CLRS text.
You need a "big number" package - either one you use or one you write yourself.
I'd recommend doing some research into "large number algorithms". You'll want to implement the C++ equivalent of Java's BigDecimal.
Another way to look at it is using the gamma function. You don't need to multiply all those values to get the right answer.
To start you off, you should store the number in some sort of array like a std::vector (a digit for each position in the array) and you need to find a certain algorithm that will calculate a factorial (maybe in some sort of specialized class). ;)
//SIMPLE FUNCTION TO COMPUTE THE FACTORIAL OF A NUMBER
//THIS ONLY WORKS UPTO N = 65
//CAN YOU SUGGEST HOW WE CAN IMPROVE IT TO COMPUTE FACTORIAL OF 400 PLEASE?
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int x); //function to compute factorial described below
int main()
{
int N; //= 150; //you can also get this as user input using cin.
cout<<"Enter intenger\n";
cin>>N;
factorial(N);
return 0;
}//end of main
int factorial(int x) //function to compute the factorial
{
int i, n;
long long unsigned results = 1;
for (i = 1; i<=x; i++)
{
results = results * i;
}
cout<<"Factorial of "<<x<<" is "<<results<<endl;
return results;
}