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
Count of all possible values of X such that A % X = B in C++
Given two integers A and B and a number X. The goal is to find the count of values that X can have so that A%X=B. For the above equation if, A==B then infinite values of X are possible, so return −1. If A < B then there would be no solution so return 0. If A>B then return count of divisors of (AB) as result.
For Example
Input
A=5, B=2
Output
Count of all possible values of X such that A % X = B are: 1
Explanation
5%3=2. So X is 3 here.
Input
A=10, B=10
Output
Count of all possible values of X such that A % X = B are: −1
Explanation
Here A==B so there are infinite solutions so −1 is returned.
Approach used in the below program is as follows −
In this approach we will calculate divisors of (A−B) using for loop from i=1 to i*i<=(A−B). If any i fully divides (A−B) then update count accordingly.
Take integers A and B as input.
If A<B then print 0 as result.
If A==B then print −1 as result.
For A>B, function possible_values(int A, int B) takes A and B and returns count of all possible values of X such that A % X = B.
Take initial count as 0 and X=A−B.
Traverse using for loop from i=1 to i*i<(A−B), for calculating divisors of X.
If any i fully divides X then take temp=i, temp_2=B−1 and if i*i!=X then set temp_2 = X / i.
If temp>B and temp_2 >B then increment count.
At the end of loop return count as result.
Example
#include <bits/stdc++.h>
using namespace std;
int possible_values(int A, int B){
int count = 0;
int X = A − B;
for (int i = 1; i * i <= A − B; i++){
if(X % i == 0){
int temp = i;
int temp_2 = B − 1;
if(i * i != X){
temp_2 = X / i;
}
if(temp > B){
count++;
}
if(temp_2 > B){
count++;
}
}
}
return count;
}
int main(){
int A = 15, B = 5;
if(A < B){
cout<<"Count of all possible values of X such that A % X = B are: "<<0;
}
else if(A == B){
cout<<"Count of all possible values of X such that A % X = B are: "<<−1;
}
else{
cout<<"Count of all possible values of X such that A % X = B are: "<<possible_values(A, B);
}
return 0;
}
Output
If we run the above code it will generate the following output −
Count of all possible values of X such that A % X = B are: 1