1362. Closest Divisors

題目描述

Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.

Return the two integers in any order.

 

Example 1:

Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.

Example 2:

Input: num = 123
Output: [5,25]

Example 3:

Input: num = 999
Output: [40,25]

 

Constraints:

  • 1 <= num <= 10^9

解析

對於數num,若i*j==num,假設i<=j,則必有i<=sqrt(num)j>=sqrt(num)

class Solution {
public:
    vector<int> closestDivisors(int num) {
        vector<int> ans(2);
        int sqr=sqrt(num+2);
        for(int i=sqr;i>=1;i--){
            if((num+1)%i==0){
                ans[0]=i;
                ans[1]=(num+1)/i;
                break;
            }
            else if((num+2)%i==0){
                ans[0]=i;
                ans[1]=(num+2)/i;
                break;
            }
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章