[LeetCode] Number of Beautiful Pairs

2748. Number of Beautiful Pairs

You are given a 0-indexed integer array nums. A pair of indices i, j where 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime.

Return the total number of beautiful pairs in nums.

Two integers x and y are coprime if there is no integer greater than 1 that divides both of them. In other words, x and y are coprime if gcd(x, y) == 1, where gcd(x, y) is the greatest common divisor of x and y.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int countBeautifulPairs(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
int x = to_string(nums[i])[0] - '0';
for(int j = i + 1; j < nums.size(); j++) {
int y = nums[j] % 10;
if(__gcd(x,y) == 1) res += 1;
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/25/PS/LeetCode/number-of-beautiful-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.