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 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.
5 is not a lucky no.
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:
|Current function call||Position after this call||Counter for next call||Next Call|
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.
- Check perfect square using addition/subtraction
- Program to check if a given number is Lucky (all digits are different)
- Find next greater number with same set of digits
- Pascal's Triangle
- Magic Square
- Count numbers that don't contain 3
- Average of a stream of numbers
- Program for Fibonacci numbers
- Print all combinations of points that can compose a given number
- Multiply two integers without using multiplication, division and bitwise operators, and no loops
- Babylonian method for square root
- Write a program to add two numbers in base 14
- Write a program to print all permutations of a given string
- Efficient way to multiply with 7
- Write an Efficient Method to Check if a Number is Multiple of 3