Skip to main content

Posts

Showing posts from September, 2014

Playing with prime numbers

A prime number is a number that is divisible only by itself, for example the first few prime numbers are 2,3,5,7,11,13,17,..... The straightforward way to find all prime numbers is to iterate through the numbers and see each number meets a specific criterion. The program does this by, Check if the number ends with a 2,4,5,6,8 or a 0. If this is the case it's not prime. Check if the number is divisible by 3 or 7, then it's not prime These 2 conditions alone doesn't suffice. For example take the number 1079, this is divisible by 13, so we have to check if each number can be divided by any other prime numbers which are lower than the number itself. But there's a shortcut. We don't have to check with every prime number lower than the number. Take the prime number 37. We take it's square root rounded down, which is 6. Then we check the prime numbers only upto 7 because otherwise we do unnecessary checks, e.g. we can check 2*6. 3*6, 5*6 but as soon as we go 7*6

B'day paradox problem

Birthday paradox problem is to fill a room with n people and get the probability of at least 2 people having the same b'day. This is given for 25 people as 1-(364.363.362....341)/(365^24). This can be done using the following snippet in C++. http://en.wikipedia.org/wiki/Birthday_problem#Calculating_the_probability void bDayParadox() {     float result = 1.0;     int numerator = 364.0;     for (int i = 0; i < 24; i++) {         result = result * (numerator / 365.0);                numerator = numerator - 1.0;     }     std::cout << 1.0-result << std::endl; }

Finding the factorial of any number

This is an interesting problem that I did to polish up my coding + analytical skills.  I required to get the factorial of any number (1 to 15 here). Because you need to handle large numbers this had to be done via a custom multiplier. Given the first few factorials: 1! = 1 2! = 2 x 1 = 2 3! = 3 x 2 x 1 = 6 4! = 4 x 3 x 2 x 1 = 24 What is the sum of the first 15 factorials, NOT INCLUDING 0!? Source : http://www.cstutoringcenter.com/problems/problems.php?id=1 Rendering...