Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1403b6d

Browse files
committed
update 1362.closest-divisors.cpp
1 parent 13e6287 commit 1403b6d

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

‎1362.closest-divisors.cpp‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* @lc app=leetcode id=1362 lang=cpp
3+
*
4+
* [1362] Closest Divisors
5+
*
6+
* https://leetcode.com/problems/closest-divisors/description/
7+
*
8+
* algorithms
9+
* Medium (54.13%)
10+
* Likes: 42
11+
* Dislikes: 23
12+
* Total Accepted: 6.4K
13+
* Total Submissions: 11.8K
14+
* Testcase Example: '8'
15+
*
16+
* Given an integer num, find the closest two integers in absolute difference
17+
* whose product equals num + 1 or num + 2.
18+
*
19+
* Return the two integers in any order.
20+
*
21+
*
22+
* Example 1:
23+
*
24+
*
25+
* Input: num = 8
26+
* Output: [3,3]
27+
* Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 =
28+
* 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
29+
*
30+
*
31+
* Example 2:
32+
*
33+
*
34+
* Input: num = 123
35+
* Output: [5,25]
36+
*
37+
*
38+
* Example 3:
39+
*
40+
*
41+
* Input: num = 999
42+
* Output: [40,25]
43+
*
44+
*
45+
*
46+
* Constraints:
47+
*
48+
*
49+
* 1 <= num <= 10^9
50+
*
51+
*
52+
*/
53+
54+
// @lc code=start
55+
class Solution {
56+
public:
57+
vector<int> closestDivisors(int num) {
58+
vector<int> ans(2, -1);
59+
int n = num+1;
60+
int diff = INT_MAX;
61+
for(int i=(int)sqrt(n); i>=1; i--){
62+
int i2= n/i;
63+
if(i2*i == n){
64+
if(abs(i-i2) < diff){
65+
diff = abs(i-i2);
66+
ans[0] = i;
67+
ans[1] = i2;
68+
}
69+
break;
70+
}
71+
}
72+
n = num+2;
73+
for(int i=(int)sqrt(n); i>=1; i--){
74+
int i2= n/i;
75+
if(i2*i == n){
76+
if(abs(i-i2) < diff){
77+
diff = abs(i-i2);
78+
ans[0] = i;
79+
ans[1] = i2;
80+
}
81+
break;
82+
}
83+
}
84+
85+
return ans;
86+
}
87+
};
88+
// @lc code=end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /