Maximum positive integer divisible by C and is in the range [A, B]
Last Updated :
23 Jun, 2022
Given three positive integers A, B, and C. The task is to find the maximum integer X > 0 such that:
- X % C = 0 and
- X must belong to the range [A, B]
Print -1 if no such number i.e. X exists.
Examples:
Input: A = 2, B = 4, C = 2
Output: 4
B is itself divisible by C.
Input: A = 5, B = 10, C = 4
Output: 8
B is not divisible by C.
So maximum multiple of 4(C) smaller than 10(B) is 8
Approach:
- If B is a multiple of C then B is the required number.
- Else get the maximum multiple of C just lesser than B which is the required answer.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int getMaxNum( int a, int b, int c)
{
if (b % c == 0)
return b;
int x = ((b / c) * c);
if (x >= a && x <= b)
return x;
else
return -1;
}
int main()
{
int a = 2, b = 10, c = 3;
cout << getMaxNum(a, b, c);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getMaxNum( int a, int b, int c)
{
if (b % c == 0 )
return b;
int x = ((b / c) * c);
if (x >= a && x <= b)
return x;
else
return - 1 ;
}
public static void main (String[] args)
{
int a = 2 , b = 10 , c = 3 ;
System.out.println(getMaxNum(a, b, c));
}
}
|
Python3
def getMaxNum(a, b, c):
if (b % c = = 0 ):
return b
x = ((b / / c) * c)
if (x > = a and x < = b):
return x
else :
return - 1
a, b, c = 2 , 10 , 3
print (getMaxNum(a, b, c))
|
C#
using System;
class GFG
{
static int getMaxNum( int a, int b, int c)
{
if (b % c == 0)
return b;
int x = ((b / c) * c);
if (x >= a && x <= b)
return x;
else
return -1;
}
public static void Main ()
{
int a = 2, b = 10, c = 3;
Console.WriteLine(getMaxNum(a, b, c));
}
}
|
PHP
<?php
function getMaxNum( $a , $b , $c )
{
if ( $b % $c == 0)
return $b ;
$x = ((int)( $b / $c ) * $c );
if ( $x >= $a && $x <= $b )
return $x ;
else
return -1;
}
$a = 2; $b = 10; $c = 3;
echo (getMaxNum( $a , $b , $c ));
?>
|
Javascript
<script>
function getMaxNum(a, b, c)
{
if (b % c == 0)
return b;
var x = (parseInt(b / c) * c);
if (x >= a && x <= b)
return x;
else
return -1;
}
var a = 2, b = 10, c = 3;
document.write( getMaxNum(a, b, c));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...