📌  相关文章
📜  可被C整除的最大正整数,范围为[A,B]

📅  最后修改于: 2021-05-04 13:16:24             🧑  作者: Mango

给定三个正整数A,B和C。任务是找到最大整数X> 0,这样:

  1. X%C = 0且
  2. X必须属于[A,B]范围

如果不存在这样的数字(即X),则打印-1

例子:

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

方法:

  • 如果B是C的倍数,则B是必需的数字。
  • 否则,得到的C的最大倍数仅比B小,这是必需的答案。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
  
// Function to return the required number
int getMaxNum(int a, int b, int c)
{
  
    // If b % c = 0 then b is the
    // required number
    if (b % c == 0)
        return b;
  
    // Else get the maximum multiple of
    // c smaller than b
    int x = ((b / c) * c);
      
    if (x >= a && x <= b)
        return x;
    else 
        return -1;
}
  
// Driver code
int main()
{
    int a = 2, b = 10, c = 3;
    cout << getMaxNum(a, b, c);
    return 0;
}


Java
// Java implementation of the above approach
import java.io.*;
  
class GFG 
{
      
// Function to return the required number
static int getMaxNum(int a, int b, int c)
{
  
    // If b % c = 0 then b is the
    // required number
    if (b % c == 0)
        return b;
  
    // Else get the maximum multiple of
    // c smaller than b
    int x = ((b / c) * c);
      
    if (x >= a && x <= b)
        return x;
    else
        return -1;
}
  
// Driver code
public static void main (String[] args) 
{
    int a = 2, b = 10, c = 3;
    System.out.println(getMaxNum(a, b, c));
}
}
  
// This Code is contributed by ajit..


Python3
# Python3 implementation of the above approach
  
# Function to return the required number
def getMaxNum(a, b, c):
  
    # If b % c = 0 then b is the
    # required number
    if (b % c == 0):
        return b
  
    # Else get the maximum multiple 
    # of c smaller than b
    x = ((b //c) * c)
      
    if (x >= a and x <= b):
        return x
    else:
        return -1
  
# Driver code
a, b, c = 2, 10, 3
print(getMaxNum(a, b, c))
  
# This code is contributed 
# by Mohit Kumar


C#
// C# implementation of the above approach
using System;
class GFG 
{
      
// Function to return the required number
static int getMaxNum(int a, int b, int c)
{
  
    // If b % c = 0 then b is the
    // required number
    if (b % c == 0)
        return b;
  
    // Else get the maximum multiple of
    // c smaller than b
    int x = ((b / c) * c);
      
    if (x >= a && x <= b)
        return x;
    else
        return -1;
}
  
// Driver code
public static void Main () 
{
    int a = 2, b = 10, c = 3;
    Console.WriteLine(getMaxNum(a, b, c));
}
}
  
// This Code is contributed by Code_Mech..


PHP
= $a && $x <= $b)
        return $x;
    else
        return -1;
}
  
// Driver code
$a = 2; $b = 10; $c = 3;
echo(getMaxNum($a, $b, $c));
  
// This Code is contributed
// by Mukul Singh
?>


输出:
9