Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers,
Take the set of integers
First, delete every second number, we get following reduced set.
Now, delete every third number, we get
1, 3, 7, 9, 13, 15, 19,….….
Continue this process indefinitely……
Any number that does NOT get deleted due to above process is called “lucky”.
Therefore, set of lucky numbers is 1, 3, 7, 13,………
Now, given an integer ‘n’, write a function to say whether this number is lucky or not.
bool isLucky(int n)
Before every iteration, if we calculate position of the given number, then in a given iteration, we can determine if the number will be deleted. Suppose calculated position for the given number is P before some iteration, and each Ith number is going to be removed in this iteration, i
f P < I then input number is lucky,
if P is such that P%I == 0 (I is a divisor of P), then input no is not lucky.
How to calculate Next position of the number:
We know that initially the position of the number is nth itself. Now any next position will be equal to the previous position minus the number of elements (or say items) removed.
That is, next_position = current_position – count of numbers removed
For example, take the case of n=13.
We have: Initial position: n, ie. 13 itself.
Now after removing every second elements , we actually removed n/2 elements. So now the position of 13 will be : n-n/2=13-6=7 (n=13), i=2
After that, we remove n/3 items. Note that n now is n=7. So position of 13 : n-n/3 = 7-7/3 = 7-2 = 5 (n=7), i=3
So next it will be : n-n/4 = 5-5/4 = 4 (n=5), i=4
So now i=5, but since position of 13 is 4 only, so it will be saved. Hence a lucky number! n=4, i=5
5 is not a lucky no.
Let’s us take an example of 19
In next step every 6th no .in sequence will be deleted. 19 will not be deleted after this step because position of 19 is 5th after this step. Therefore, 19 is lucky. Let’s see how above C code finds out:
When isLucky(6) is called, it returns 1 (because counter > n).
Please write comments if you find any bug in the given programs or other ways to solve the same problem.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.