Some formulas and functions ocaml - beginner - ocaml

So, I've got to write a recursive function which will count the number of "1"'s are in an any given number. For this part, I managed to create the function which converts a decimal to binary :
if dec = 0 then 0
else dec mod 2 + 10 *f(dec/2)
;;
but I've got no idea how to make the program check each digit and even count the wanted ones.
And I have to write a function which has to calculate the sum of the 1/(n!) series. Again, I tried for hours, but the best I could do was :
if n <= 1. then 1.
else 1./.(n*.e(n-.1.)) +. (e(n-.1.))
;;
which doesn't work the right way cause I guess the formula isn't right.
Can somebody help me? ;-; Please, I want to understand the way this works.

For the first question, you probably want to generate a list of bits in a first time rather than an integer. It should make further bit manipulation easier to handle.
For the second question, you should write a separate factorial function first and use it in your definition of e. Currently, you are mixing the sum computation and the factorial computation.

Related

Efficient way for generating coprime pairs

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.

Define an homemade pow function as an exercise

On my IT lessons i got this task:
Write function where user puts integer m (m>1) and non-negative n and
the function returns std::pow(n, 1.0/m). You cant use any library.
Which means, i have to use pow function... but i can't use it.
Since its not 2^2 or 2^7, i cant use simple for loop.
I've tried doing anything like adding, multiplication, nothing worked anywhere near.
Any ideas?
FYI:
It's not my homework, teacher just gave me this task to learn something.
std::pow(n, 1.0/m) is the m-th root of n. You can find an helpful algorithm of how to implement it on wikipedia:
Make an initial guess x0
Set x = 1.0/m * [ (n-1)*x + n/pow(x,m-1) ]1
Repeat step 2 until x is only changed a little or maxiter has been reached.
1) Obviously, you'll need to define pow(x,y) for integer y, which is trivial.

Recursion to output possible outcomes of N number of coin flips

I'm trying to use recursion to output the possible outcomes of N number of coin flips. For instance, if I flip a coin 3 times the possible outputs could be TTT, TTH, THT, THH, HTT, HTH, HHT, and HHH. I'm not looking for an answer but a push in the right direction. Would this be best done with a character array? Or assigning H and T integer values?
Alternatively, since it can only ever be heads or tails, you could use a boolean value. This would be more efficient for memory and will also help avoid the need for error checking. But there is no single way of doing it, experiment and see what works best.
I would say integers. Look up permutations and simple combinatorics if you​haven't already. Remember, recursion operates on the principal of breaking a big problem into smaller ones.

Find the numbers missing

If we have an array of all the numbers up to N (N < 10), what is the best way to find all the numbers that are missing.
Example:
N = 5
1 5 3 2 3
Output: 1 5 4 2 3
In the ex, the number 4 was the missing one and there were 2 3s, so we replaced the first one with 4 and now the array is complete - all the numbers up to 5 are there.
Is there any simple algorithm that can do this ?
Since N is really small, you can use F[i] = k if number i appears k times.
int F[10]; // make sure to initialize it to 0
for ( int i = 0; i < N; ++i )
++F[ numbers[i] ];
Now, to replace the duplicates, traverse your number array and if the current number appears more than once, decrement its count and replace it with a number that appears 0 times and increment that number's count. You can keep this O(N) if you keep a list of numbers that don't appear at all. I'll let you figure out what exactly needs to be done, as this sounds like homework.
Assume all numbers within the range 1 ≤ x ≤ N.
Keep 2 arrays of size N. output, used (as an associative array). Initialize them all to 0.
Scan from the right, fill in values to output unless it is used.
Check for unused values, and put them into the empty (zero) slots of output in order.
O(N) time complexity, O(N) space complexity.
You can use a set data structure - one for all the numbers up to N, one for the numbers you actually saw, and use a set difference.
One way to do this would be to look at each element of the array in sequence, and see whether that element has been seen before in elements that you've already checked. If so, then change that number to one you haven't seen before, and proceed.
Allow me to introduce you to my friend Schlemiel the Painter. Discovery of a more efficient method is left as a challenge for the reader.
This kind of looks like homework, please let us know if it isn't. I'll give you a small hint, and then I'll improve my answer if you confirm this isn't homework.
My tip for now is this: If you were to do this by hand, how would you do it? Would you write out an extra list of numbers of some time, would you read through the list (how many times?)? etc.
For simple problems, sometimes modelling your algorithm after an intuitive by-hand approach can work well.
Here's a link I read just today that may be helpful.
http://research.swtch.com/2008/03/using-uninitialized-memory-for-fun-and.html

Calculating large factorials in C++

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