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
1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,……

First, delete every second number, we get following reduced set.
1,3,5,7,9,11,13,15,17,19,…………

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)
[ad type=”banner”]

Algorithm:
Before every iteration, if we calculate position of the given no, then in a given iteration, we can determine if the no will be deleted. Suppose calculated position for the given no. is P before some iteration, and each Ith no. is going to be removed in this iteration, if P < I then input no is lucky, if P is such that P%I == 0 (I is a divisor of P), then input no is not lucky.

Recursive Way:

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%23define%20bool%20int%0A%20%0A%2F*%20Returns%201%20if%20n%20is%20a%20lucky%20no.%20ohterwise%20returns%200*%2F%0Abool%20isLucky(int%20n)%0A%7B%0A%20%20static%20int%20counter%20%3D%202%3B%0A%20%0A%20%20%2F*variable%20next_position%20is%20just%20for%20readability%20of%0A%20%20%20%20%20the%20program%20we%20can%20remove%20it%20and%20use%20n%20only%20*%2F%0A%20%20int%20next_position%20%3D%20n%3B%0A%20%20if(counter%20%3E%20n)%0A%20%20%20%20return%201%3B%0A%20%20if(n%25counter%20%3D%3D%200)%0A%20%20%20%20return%200%3B%20%20%20%20%20%20%0A%20%0A%20%2F*calculate%20next%20position%20of%20input%20no*%2F%0A%20%20next_position%20-%3D%20next_position%2Fcounter%3B%0A%20%20%20%0A%20%20counter%2B%2B%3B%0A%20%20return%20isLucky(next_position)%3B%0A%7D%0A%20%0A%2F*Driver%20function%20to%20test%20above%20function*%2F%0Aint%20main()%0A%7B%0A%20%20int%20x%20%3D%205%3B%0A%20%20if(%20isLucky(x)%20)%0A%20%20%20%20printf(%22%25d%20is%20a%20lucky%20no.%22%2C%20x)%3B%0A%20%20else%0A%20%20%20%20printf(%22%25d%20is%20not%20a%20lucky%20no.%22%2C%20x)%3B%0A%20%20getchar()%3B%0A%7D” message=”C” highlight=”” provider=”manual”/]

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.

[ad type=”banner”]