Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find Nth term divisible by a or b in C++
In this problem, we are given three numbers A, B, and N. Our task is to create a program to find Nth term divisible by A or B in C++.
Problem Description
The Nth Term divisible by A or B. Here, we will find the term n number term which is divisible by number A or B. For this, we will count till nth numbers that are divisible by A or B.
Let’s take an example to understand the problem,
Input
A = 4, B = 3, N = 5
Output
9
Explanation
The terms the are divisible by 3 and 4 are −
3, 4, 6, 8, 9, 12, …
5th term is 9.
Solution Approach
To find the nth term that is divisible by A or B. We can simply find numbers divisible by A or B and the nth term in the series is our answer.
Example
#include<iostream>
using namespace std;
int findNTerm(int N, int A, int B) {
int count = 0;
int num = 1;
while( count < N){
if(num%A == 0 || num%B == 0)
count++;
if(count == N)
return num;
num++;
}
return 0;
}
int main(){
int N = 12, A = 3, B = 4;
cout<<N<<"th term divisible by "<<A<<" or "<<B<<" is "<<findNTerm(N, A, B)<<endl;
}
Output
12th term divisible by 3 or 4 is 24
Another approach to solving the problem could be using the Binary search to find the Nth element which is divisible by A or B. We will find the Nth term using the formula−
NTerm = maxNum/A + maxNum/B + maxNum/lcm(A,B)
And based on the value of Nterm, we will check if we need to traverse in the numbers less than maxNum or greater than maxNum.
Example
#include <iostream>
using namespace std;
int findLCM(int a, int b) {
int LCM = a, i = 2;
while(LCM % b != 0) {
LCM = a*i;
i++;
}
return LCM;
}
int findNTerm(int N, int A, int B) {
int start = 1, end = (N*A*B), mid;
int LCM = findLCM(A, B);
while (start < end) {
mid = start + (end - start) / 2;
if ( ((mid/A) + (mid/B) - (mid/LCM)) < N)
start = mid + 1;
else
end = mid;
}
return start;
}
int main() {
int N = 12, A = 3, B = 4;
cout<<N<<"th term divisible by "<<A<<" or "<<B<<" is "<<findNTerm(N, A, B);
}
Output
12th term divisible by 3 or 4 is 24