Given three positive integers x, y and n, the task is to find count of all numbers from 1 to n that can be formed using x and y. A number can be formed using x and y if we can get it by adding any number of occurrences of x and/or y.
Input : n = 10, x = 2, y = 3 Output : 9 We can form 9 out of 10 numbers using 2 and 3 2 = 2, 3 = 3, 4 = 2+2, 5 = 2+3, 6 = 3+3 7 = 2+2+3, 8 = 3+3+2, 9 = 3+3+3 and 10 = 3+3+2+2. Input : n = 10, x = 5, y = 7 Output : 3 We can form 3 out of 10 numbers using 5 and 7 The numbers are 5, 7 and 10 Input : n = 15, x = 5, y = 7 Output : 6 We can form 6 out of 10 numbers using 5 and 7. The numbers are 5, 7, 10, 12, 14 and 15. Input : n = 15, x = 2, y = 4 Output : 7
A simple solution is to write a recursive code that starts with 0 and makes two recursive calls. One recursive call adds x and other adds y. This way we count total numbers. We need to make sure a number is counted multiple times.
An efficient solution solution is to use a boolean array arr of size n+1. An entry arr[i] = true is going to mean that i can be formed using x and y. We initialize arr[x] and arr[y] as true if x and y are smaller than or equal to n. We start traversing the array from smaller of two numbers and mark all numbers one by one that can be formed using x and y. Below is the implementation.
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Count digits in a factorial | Set 2
- How to swap two numbers without using a temporary variable?
- Lucky Numbers
- Ugly Numbers
- Write a program to add two numbers in base 14
- Count of Binary Digit numbers smaller than N
- Program for Fibonacci numbers
- Average of a stream of numbers
- Add two numbers without using arithmetic operators
- To find sum of two numbers without using any operator
- Count numbers that don't contain 3
- Count the number of possible triangles
- Count numbers with same first and last digits
- Count digits in given number N which divide N
- Russian Peasant (Multiply two numbers using bitwise operators)