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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Program to check if a given number is Lucky (all digits are different)
- Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
- Numbers less than N which are product of exactly two distinct prime numbers
- Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K
- Check if a given pair of Numbers are Betrothed numbers or not
- Count numbers which can be constructed using two numbers
- Count numbers which are divisible by all the numbers from 2 to 10
- Maximum sum of distinct numbers such that LCM of these numbers is N
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Add two numbers using ++ and/or --
- D Numbers
- Self Numbers
- Sum of first n even numbers
- Hailstone Numbers
- GCD of factorials of two numbers
- Betrothed numbers