Largest number smaller than or equal to N divisible by K
Given a number N and a number K, the task is to find the largest number smaller than or equal to N which is divisible by K.
Examples:
Input: N = 45, K = 6
Output: 42
42 is the largest number smaller than
or equal to 45 which is divisible by 6.
Input: N = 11, K = 3
Output: 9
Approach: The idea is to divide the N by K. If the remainder is 0 then print N else print N – remainder.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findNum( int N, int K)
{
int rem = N % K;
if (rem == 0)
return N;
else
return N - rem;
}
int main()
{
int N = 45, K = 6;
cout << "Largest number smaller than or equal to " << N
<< "\nthat is divisible by " << K << " is " << findNum(N, K);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG
{
static int findNum( int N, int K)
{
int rem = N % K;
if (rem == 0 )
return N;
else
return N - rem;
}
public static void main(String args[])
{
int N = 45 , K = 6 ;
System.out.print( "Largest number smaller " +
"than or equal to " + N +
"\nthat is divisible by " + K +
" is " + findNum(N, K));
}
}
|
Python3
def findNum(N, K):
rem = N % K
if (rem = = 0 ):
return N
else :
return N - rem
if __name__ = = '__main__' :
N = 45
K = 6
print ( "Largest number smaller than or equal to" +
str (N) + "that is divisible by" + str (K) +
"is" , findNum(N, K))
|
C#
using System;
class GFG
{
static int findNum( int N, int K)
{
int rem = N % K;
if (rem == 0)
return N;
else
return N - rem;
}
public static void Main()
{
int N = 45, K = 6;
Console.Write( "Largest number smaller " +
"than or equal to " + N +
"\nthat is divisible by " + K +
" is " + findNum(N, K));
}
}
|
PHP
<?php
function findNum( $N , $K )
{
$rem = $N % $K ;
if ( $rem == 0)
return $N ;
else
return $N - $rem ;
}
$N = 45 ;
$K = 6 ;
echo "Largest number smaller than or equal to " , $N ,
"\nthat is divisible by " , $K , " is " ,
findNum( $N , $K );
?>
|
Javascript
<script>
function findNum(N, K)
{
var rem = N % K;
if (rem == 0)
return N;
else
return N - rem;
}
var N = 45, K = 6;
document.write( "Largest number smaller than or equal to " + N
+ "<br>that is divisible by " + K + " is " + findNum(N, K));
</script>
|
Output:
Largest number smaller than or equal to 45
that is divisible by 6 is 42
Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
25 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...