Largest number less than or equal to Z that leaves a remainder X when divided by Y
Given three integers x, y, z, the task is to find the largest non-negative number less than or equal to z that leaves a remainder x when divided by y (Given x < y). If no such number exists then the output will be -1.
Examples:
Input: x = 1, y = 5, z = 8
Output: 6
Explanation:
6 is the largest number less than 8
which when divided by 5
leaves a remainder 1.
Input: x = 4, y = 6, z = 3
Output: -1
Explanation:
Since no such number exists the output is -1
Approach: To solve the problem mentioned above the very first observation is if x > z then answer will not be possible, so output will be -1.
Let the required number be p. Following are the two equations for solving the problem:
- p * y + x = 0
- p * y <= (z – x)
In order to find the answer, we need to find the value of p. So,
p = (z - x) / y
After calculating p we can simply find the answer which is
p * y + x
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int get( int x, int y, int z)
{
if (x > z)
return -1;
int val = z - x;
int div = (z - x) / y;
int ans = div * y + x;
return ans;
}
int main()
{
int x = 1, y = 5, z = 8;
cout << get(x, y, z) << "\n" ;
return 0;
}
|
Java
class GFG{
static int get( int x, int y, int z)
{
if (x > z)
return - 1 ;
int val = z - x;
int div = (z - x) / y;
int ans = div * y + x;
return ans;
}
public static void main(String[] args)
{
int x = 1 , y = 5 , z = 8 ;
System.out.print(get(x, y, z)+ "\n" );
}
}
|
Python3
def get(x, y, z):
if (x > z):
return - 1
val = z - x
div = (z - x) / / y
ans = div * y + x
return ans
x = 1
y = 5
z = 8
print (get(x, y, z))
|
C#
using System;
class GFG{
static int get ( int x, int y, int z)
{
if (x > z)
return -1;
int val = z - x;
int div = (z - x) / y;
int ans = div * y + x;
return ans;
}
public static void Main(String[] args)
{
int x = 1, y = 5, z = 8;
Console.Write( get (x, y, z)+ "\n" );
}
}
|
Javascript
<script>
function get(x, y, z)
{
if (x > z)
return -1;
let val = z - x;
let div = Math.floor((z - x) / y);
let ans = div * y + x;
return ans;
}
let x = 1, y = 5, z = 8;
document.write(get(x, y, z)+ "\n" );
</script>
|
Time Complexity: O(1 )
Auxiliary Space: O(1)
Last Updated :
01 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...