Find the greatest divisor which is less than or equal to the given number.
Example:
Input: n = 24, k = 7
Output: 6
Approach
Java
public class GreatestDivisorNumber {public static void main(String[] args) {int n = 24;int k = 7;System.out.println(greatestDivisorLessThanK(n, k));}// function to find the greatest divisor// which is less than or equal to other numberstatic int greatestDivisorLessThanK(int n, int k) {int ans = -1;// find all divisors of the numberfor (int i = 1; i * i <= n; i++) {if (n % i == 0) {// if the number is sameif (n / i == i) {// update answerif (n / i <= k) {ans = Math.max(ans, n / i);}} else {// update answerif (n / i <= k) {ans = Math.max(ans, n / i);}// update answerelse if (i <= k) {ans = Math.max(ans, i);}}}}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the greatest divisor//which is less than or equal to other numberint greatestDivisorLessThanK(int n,int k){int ans=-1;//find all divisors of the numberfor(int i=1;i*i<=n;i++){if(n%i==0){//if the number is sameif(n/i==i){//update answerif(n/i<=k){ans= max(ans,n/i);}}else{//update answerif(n/i<=k){ans=max(ans,n/i);}//update answerelse if(i<=k){ans=max(ans,i);}}}}return ans;}int main(){int n=24;int k=7;cout<<greatestDivisorLessThanK(n,k);return 0;}
No comments:
Post a Comment