Given an integer n, the task is to count the total lucky numbers smaller than or equal to n. A number is said to be lucky if it has all contagious number of 1’s in binary representation from the beginning. For example 1, 3, 7, 15 are lucky numbers, and 2, 5 and 9 are not lucky numbers.
Input :n = 7 Output :3 1, 3 and 7 are lucky numbers Input :n = 17 Output :4
Approach:one approach is that first we find out the binary representation of each number and than check for contagious number of 1’s for each number, but this approach is time consuming and can give tle if the constraints are two large, Efficient approach can be find out by observing the numbers, we can say that every ith lucky number can be found by the formula 2i-1, and by iterating a loop upto number less than equal to n we can find out the total lucky numbers.
Below is the implementation of above approach
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.
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Longest common substring in binary representation of two numbers
- C program to count zeros and ones in binary representation of a number
- Count of total bits toggled/flipped in binary representation of 0 to N
- Count number of trailing zeros in Binary representation of a number using Bitset
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Count of Binary Digit numbers smaller than N
- Count of N-bit binary numbers without leading zeros
- Maximum 0's between two immediate 1's in binary representation
- Binary representation of next number
- Largest number with binary representation is m 1's and m-1 0's
- Binary representation of previous number
- Maximum distance between two 1's in Binary representation of N
- Next greater number than N with exactly one bit different in binary representation of N
- Check if binary representation of a number is palindrome
- Decimal representation of given binary string is divisible by 10 or not
- Prime Number of Set Bits in Binary Representation | Set 2
- Length of the Longest Consecutive 1s in Binary Representation
- Prime Number of Set Bits in Binary Representation | Set 1
- Decimal representation of given binary string is divisible by 5 or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.