<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>gcd Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/gcd/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/gcd/</link>
	<description></description>
	<lastBuildDate>Tue, 08 Mar 2022 12:19:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>gcd Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/gcd/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2197. Replace Non-Coprime Numbers in Array</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 08 Mar 2022 12:18:45 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[co-prime]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[lcm]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9561</guid>

					<description><![CDATA[<p>You are given an array of integers&#160;nums. Perform the following steps: Find&#160;any&#160;two&#160;adjacent&#160;numbers in&#160;nums&#160;that are&#160;non-coprime. If no such numbers are found,&#160;stop&#160;the process. Otherwise, delete the two&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/">花花酱 LeetCode 2197. Replace Non-Coprime Numbers in Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of integers&nbsp;<code>nums</code>. Perform the following steps:</p>



<ol><li>Find&nbsp;<strong>any</strong>&nbsp;two&nbsp;<strong>adjacent</strong>&nbsp;numbers in&nbsp;<code>nums</code>&nbsp;that are&nbsp;<strong>non-coprime</strong>.</li><li>If no such numbers are found,&nbsp;<strong>stop</strong>&nbsp;the process.</li><li>Otherwise, delete the two numbers and&nbsp;<strong>replace</strong>&nbsp;them with their&nbsp;<strong>LCM (Least Common Multiple)</strong>.</li><li><strong>Repeat</strong>&nbsp;this process as long as you keep finding two adjacent non-coprime numbers.</li></ol>



<p>Return&nbsp;<em>the&nbsp;<strong>final</strong>&nbsp;modified array.</em>&nbsp;It can be shown that replacing adjacent non-coprime numbers in&nbsp;<strong>any</strong>&nbsp;arbitrary order will lead to the same result.</p>



<p>The test cases are generated such that the values in the final array are&nbsp;<strong>less than or equal</strong>&nbsp;to&nbsp;<code>10<sup>8</sup></code>.</p>



<p>Two values&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>&nbsp;are&nbsp;<strong>non-coprime</strong>&nbsp;if&nbsp;<code>GCD(x, y) &gt; 1</code>&nbsp;where&nbsp;<code>GCD(x, y)</code>&nbsp;is the&nbsp;<strong>Greatest Common Divisor</strong>&nbsp;of&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [6,4,3,2,7,6,2]
<strong>Output:</strong> [12,7,6]
<strong>Explanation:</strong> 
- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [<strong><u>12</u></strong>,3,2,7,6,2].
- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [<strong><u>12</u></strong>,2,7,6,2].
- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [<strong><u>12</u></strong>,7,6,2].
- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,<strong>6</strong>].
There are no more adjacent non-coprime numbers in nums.
Thus, the final modified array is [12,7,6].
Note that there are other ways to obtain the same resultant array.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,2,1,1,3,3,3]
<strong>Output:</strong> [2,1,1,3]
<strong>Explanation:</strong> 
- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,<strong>3</strong>,3].
- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,<strong>3</strong>].
- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [<strong>2</strong>,1,1,3].
There are no more adjacent non-coprime numbers in nums.
Thus, the final modified array is [2,1,1,3].
Note that there are other ways to obtain the same resultant array.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li>The test cases are generated such that the values in the final array are&nbsp;<strong>less than or equal</strong>&nbsp;to&nbsp;<code>10<sup>8</sup></code>.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>&#8220;&#8221;&#8221;It can be shown that replacing adjacent non-coprime numbers in&nbsp;<strong>any</strong>&nbsp;arbitrary order will lead to the same result.&#8221;&#8221;&#8221;</p>



<p>So that we can do it in one pass from left to right using a stack/vector.</p>



<p>Push the current number onto stack, and merge top two if they are not co-prime.</p>



<p>Time complexity: O(nlogm)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; replaceNonCoprimes(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; ans;
    for (int x : nums) {
      ans.push_back(x);
      while (ans.size() &gt; 1) {
        const int n1 = ans[ans.size() - 1]; 
        const int n2 = ans[ans.size() - 2]; 
        const int d = gcd(n1, n2);
        if (d == 1) break;
        ans.pop_back();
        ans.pop_back();
        ans.push_back(n1 / d * n2);
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/">花花酱 LeetCode 2197. Replace Non-Coprime Numbers in Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2183. Count Array Pairs Divisible by K</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-2183-count-array-pairs-divisible-by-k/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-2183-count-array-pairs-divisible-by-k/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Mar 2022 03:49:45 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9531</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums&#160;of length&#160;n&#160;and an integer&#160;k, return&#160;the&#160;number of pairs&#160;(i, j)&#160;such that: 0 &#60;= i &#60; j &#60;= n - 1&#160;and nums[i] * nums[j]&#160;is divisible by&#160;k.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2183-count-array-pairs-divisible-by-k/">花花酱 LeetCode 2183. Count Array Pairs Divisible by K</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;and an integer&nbsp;<code>k</code>, return&nbsp;<em>the&nbsp;<strong>number of pairs</strong></em>&nbsp;<code>(i, j)</code>&nbsp;<em>such that:</em></p>



<ul><li><code>0 &lt;= i &lt; j &lt;= n - 1</code>&nbsp;<em>and</em></li><li><code>nums[i] * nums[j]</code>&nbsp;<em>is divisible by</em>&nbsp;<code>k</code>.</li></ul>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4,5], k = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> 
The 7 pairs of indices whose corresponding products are divisible by 2 are
(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).
Their products are 2, 4, 6, 8, 10, 12, and 20 respectively.
Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.    
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], k = 5
<strong>Output:</strong> 0
<strong>Explanation:</strong> There does not exist any pair of indices whose corresponding product is divisible by 5.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Math</strong></h2>



<p>a * b % k == 0 &lt;=> gcd(a, k) * gcd(b, k) == 0</p>



<p>Use a counter of gcd(x, k) so far to compute the number of pairs.</p>



<p>Time complexity: O(n*f), where f is the number of gcds, f &lt;= 128 for x &lt;= 1e5<br>Space complexity: O(<meta charset="utf-8">f)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long countPairs(vector&lt;int&gt;&amp; nums, int k) {
    unordered_map&lt;int, int&gt; m;
    long long ans = 0;
    for (int x : nums) {
      long long d1 = gcd(x, k);
      for (const auto&amp; [d2, c] : m)
        if (d1 * d2 % k == 0) ans += c;
      ++m[d1];
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2183-count-array-pairs-divisible-by-k/">花花酱 LeetCode 2183. Count Array Pairs Divisible by K</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-2183-count-array-pairs-divisible-by-k/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1998. GCD Sort of an Array</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1998-gcd-sort-of-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1998-gcd-sort-of-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 06:49:23 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[prime]]></category>
		<category><![CDATA[sqrt]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9383</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums, and you can perform the following operation&#160;any&#160;number of times on&#160;nums: Swap the positions of two elements&#160;nums[i]&#160;and&#160;nums[j]&#160;if&#160;gcd(nums[i], nums[j]) &#62; 1&#160;where&#160;gcd(nums[i],&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1998-gcd-sort-of-an-array/">花花酱 LeetCode 1998. GCD Sort of an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>, and you can perform the following operation&nbsp;<strong>any</strong>&nbsp;number of times on&nbsp;<code>nums</code>:</p>



<ul><li>Swap the positions of two elements&nbsp;<code>nums[i]</code>&nbsp;and&nbsp;<code>nums[j]</code>&nbsp;if&nbsp;<code>gcd(nums[i], nums[j]) &gt; 1</code>&nbsp;where&nbsp;<code>gcd(nums[i], nums[j])</code>&nbsp;is the&nbsp;<strong>greatest common divisor</strong>&nbsp;of&nbsp;<code>nums[i]</code>&nbsp;and&nbsp;<code>nums[j]</code>.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if it is possible to sort&nbsp;</em><code>nums</code><em>&nbsp;in&nbsp;<strong>non-decreasing</strong>&nbsp;order using the above swap method, or&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [7,21,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [<strong>21</strong>,<strong>7</strong>,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [<strong>3</strong>,7,<strong>21</strong>]
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,2,6,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to sort the array because 5 cannot be swapped with any other element.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,5,9,3,15]
<strong>Output:</strong> true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [<strong>15</strong>,5,9,3,<strong>10</strong>]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [<strong>3</strong>,5,9,<strong>15</strong>,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,<strong>10</strong>,<strong>15</strong>]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li><li><code>2 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Union-Find</strong></h2>



<p>Let nums[j]&#8217;s target position be i. In order to put nums[j] to pos i by swapping. nums[i] and nums[j] must be in the same connected component. There is an edge between two numbers if they have gcd > 1.</p>



<p>We union two numbers if their have gcd > 1. However, it will be TLE if we do all pairs . Thus, for each number, we union it with its divisors instead.</p>



<p>Time complexity: O(n<sup>2</sup>) TLE -> O(sum(sqrt(nums[i]))) &lt;= O(n*sqrt(m))<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool gcdSort(vector&lt;int&gt;&amp; nums) {
    const int m = *max_element(begin(nums), end(nums));
    const int n = nums.size();
    
    vector&lt;int&gt; p(m + 1);
    iota(begin(p), end(p), 0);
  
    function&lt;int(int)&gt; find = [&amp;](int x) {
      return p[x] == x ? x : (p[x] = find(p[x]));
    };
  
    for (int x : nums)
      for (int d = 2; d &lt;= sqrt(x); ++d)
        if (x % d == 0)
          p[find(x)] = p[find(x / d)] = find(d);

    vector&lt;int&gt; sorted(nums);
    sort(begin(sorted), end(sorted));
    
    for (int i = 0; i &lt; n; ++i)
      if (find(sorted[i]) != find(nums[i])) 
        return false;

    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1998-gcd-sort-of-an-array/">花花酱 LeetCode 1998. GCD Sort of an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-1998-gcd-sort-of-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1979. Find Greatest Common Divisor of Array</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1979-find-greatest-common-divisor-of-array/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1979-find-greatest-common-divisor-of-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 23:16:50 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[minmax_element]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9355</guid>

					<description><![CDATA[<p>Given an integer array&#160;nums, return&#160;the&#160;greatest common divisor&#160;of the smallest number and largest number in&#160;nums. The&#160;greatest common divisor&#160;of two numbers is the largest positive integer that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1979-find-greatest-common-divisor-of-array/">花花酱 LeetCode 1979. Find Greatest Common Divisor of Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>, return<strong>&nbsp;</strong><em>the&nbsp;<strong>greatest common divisor</strong>&nbsp;of the smallest number and largest number in&nbsp;</em><code>nums</code>.</p>



<p>The&nbsp;<strong>greatest common divisor</strong>&nbsp;of two numbers is the largest positive integer that evenly divides both numbers.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,5,6,9,10]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [7,5,6,8,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= nums[i] &lt;= 1000</code></li></ul>



<h2><strong>Solution:</strong></h2>



<p>Use <a href="https://en.cppreference.com/w/cpp/algorithm/minmax_element" target="_blank" rel="noreferrer noopener">std::minmax_element</a> and <a href="https://en.cppreference.com/w/cpp/numeric/gcd" target="_blank" rel="noreferrer noopener">std::gcd</a></p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findGCD(vector&lt;int&gt;&amp; nums) {
    auto p = minmax_element(begin(nums), end(nums));     
    return gcd(*p.first, *p.second);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1979-find-greatest-common-divisor-of-array/">花花酱 LeetCode 1979. Find Greatest Common Divisor of Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1979-find-greatest-common-divisor-of-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1819. Number of Different Subsequences GCDs</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1819-number-of-different-subsequences-gcds/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1819-number-of-different-subsequences-gcds/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 07 Apr 2021 02:34:22 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8328</guid>

					<description><![CDATA[<p>You are given an array&#160;nums&#160;that consists of positive integers. The&#160;GCD&#160;of a sequence of numbers is defined as the greatest integer that divides&#160;all&#160;the numbers in the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1819-number-of-different-subsequences-gcds/">花花酱 LeetCode 1819. Number of Different Subsequences GCDs</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an array&nbsp;<code>nums</code>&nbsp;that consists of positive integers.</p>



<p>The&nbsp;<strong>GCD</strong>&nbsp;of a sequence of numbers is defined as the greatest integer that divides&nbsp;<strong>all</strong>&nbsp;the numbers in the sequence evenly.</p>



<ul><li>For example, the GCD of the sequence&nbsp;<code>[4,6,16]</code>&nbsp;is&nbsp;<code>2</code>.</li></ul>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p>



<ul><li>For example,&nbsp;<code>[2,5,10]</code>&nbsp;is a subsequence of&nbsp;<code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>number</strong>&nbsp;of&nbsp;<strong>different</strong>&nbsp;GCDs among all&nbsp;<strong>non-empty</strong>&nbsp;subsequences of</em>&nbsp;<code>nums</code>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/17/image-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [6,10,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,15,40,5,6]
<strong>Output:</strong> 7
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Math</strong></h2>



<p>Enumerate all possible gcds (1 to max(nums)), and check whether there is a subset of the numbers that can form a given gcd i.<br>If we want to check whether 10 is a valid gcd, we found all multipliers of 10 in the array and compute their gcd.<br>ex1  gcd(10, 20, 30) = 10, true<br>ex2 gcd(20, 40, 80) = 20, false</p>



<p>Time complexity: O(mlogm)<br>Space complexity: O(m)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countDifferentSubsequenceGCDs(vector&lt;int&gt;&amp; nums) {
    const int kMax = *max_element(begin(nums), end(nums));
    vector&lt;int&gt; s(kMax + 1);
    for (int x : nums) s[x] = 1;    
    int ans = 0;
    for (int i = 1; i &lt;= kMax; ++i) {
      int g = 0;
      for (int j = i; j &lt;= kMax; j += i)
        if (s[j]) g = gcd(g, j);
      ans += g == i;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1819-number-of-different-subsequences-gcds/">花花酱 LeetCode 1819. Number of Different Subsequences GCDs</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1819-number-of-different-subsequences-gcds/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1447. Simplified Fractions</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1447-simplified-fractions/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1447-simplified-fractions/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 18 May 2020 01:45:57 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6782</guid>

					<description><![CDATA[<p>Given an integer&#160;n, return a list of all&#160;simplified&#160;fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to&#160;n. The fractions can be in&#160;any&#160;order. Example&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1447-simplified-fractions/">花花酱 LeetCode 1447. Simplified Fractions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an integer&nbsp;<code>n</code>, return a list of all&nbsp;<strong>simplified</strong>&nbsp;fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to&nbsp;<code>n</code>. The fractions can be in&nbsp;<strong>any</strong>&nbsp;order.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> ["1/2"]
<strong>Explanation: </strong>"1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3
<strong>Output:</strong> ["1/2","1/3","2/3"]
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4
<strong>Output:</strong> ["1/2","1/3","1/4","2/3","3/4"]
<strong>Explanation: </strong>"2/4" is not a simplified fraction because it can be simplified to "1/2".</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1
<strong>Output:</strong> []
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 100</code></li></ul>



<h2><strong>Solution: GCD</strong></h2>



<p>if gcd(a, b) == 1 then a/b is a simplified frication.</p>



<p>std::gcd is available since c++17.</p>



<p>Time complexity: O(n^2logn)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;string&gt; simplifiedFractions(int n) {
    vector&lt;string&gt; ans;
    for (int i = 1; i &lt; n; ++i)
      for (int j = i + 1; j &lt;= n; ++j)
        if (gcd(i, j) == 1)
          ans.push_back(to_string(i) + &quot;/&quot; + to_string(j));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1447-simplified-fractions/">花花酱 LeetCode 1447. Simplified Fractions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1447-simplified-fractions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 365. Water and Jug Problem</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-365-water-and-jug-problem/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-365-water-and-jug-problem/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Mar 2020 07:52:12 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(logn)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6432</guid>

					<description><![CDATA[<p>You are given two jugs with capacities&#160;x&#160;and&#160;y&#160;litres. There is an infinite amount of water supply available. You need to determine whether it is possible to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-365-water-and-jug-problem/">花花酱 LeetCode 365. Water and Jug Problem</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given two jugs with capacities&nbsp;<em>x</em>&nbsp;and&nbsp;<em>y</em>&nbsp;litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly&nbsp;<em>z</em>&nbsp;litres using these two jugs.</p>



<p>If&nbsp;<em>z</em>&nbsp;liters of water is measurable, you must have&nbsp;<em>z</em>&nbsp;liters of water contained within&nbsp;<strong>one or both buckets</strong>&nbsp;by the end.</p>



<p>Operations allowed:</p>



<ul><li>Fill any of the jugs completely with water.</li><li>Empty any of the jugs.</li><li>Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.</li></ul>



<p><strong>Example 1:</strong>&nbsp;(From the famous&nbsp;<a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg" target="_blank" rel="noreferrer noopener"><em>&#8220;Die Hard&#8221;</em>&nbsp;example</a>)</p>



<pre class="wp-block-preformatted;crayon:false">Input: x = 3, y = 5, z = 4
Output: True
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false">Input: x = 2, y = 6, z = 5
Output: False</pre>



<h2><strong>Solution: Math</strong></h2>



<p>special case 1: x == z or y == z or x + y == z: return True<br>special case 2: x + y &lt; z: return False<br>normal case: z must be a factor of gcd(x, y)</p>



<p>Time complexity: O(log(min(x, y))<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool canMeasureWater(int x, int y, int z) {
    if (x == z || y == z || x + y == z) return true;
    if (x + y &lt; z) return false;
    return z % gcd(x, y) == 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-365-water-and-jug-problem/">花花酱 LeetCode 365. Water and Jug Problem</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-365-water-and-jug-problem/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1250. Check If It Is a Good Array</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1250-check-if-it-is-a-good-array/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1250-check-if-it-is-a-good-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 08 Nov 2019 16:48:38 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5806</guid>

					<description><![CDATA[<p>Given an array&#160;nums&#160;of&#160;positive integers. Your task is to select some subset of&#160;nums, multiply each element by an integer and add all these numbers.&#160;The array is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1250-check-if-it-is-a-good-array/">花花酱 LeetCode 1250. Check If It Is a Good Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array&nbsp;<code>nums</code>&nbsp;of&nbsp;positive integers. Your task is to select some subset of&nbsp;<code>nums</code>, multiply each element by an integer and add all these numbers.&nbsp;The array is said to be&nbsp;<strong>good&nbsp;</strong>if you can obtain a sum of&nbsp;<code>1</code>&nbsp;from the array by any possible subset and multiplicand.</p>



<p>Return&nbsp;<code>True</code>&nbsp;if the array is&nbsp;<strong>good&nbsp;</strong>otherwise&nbsp;return&nbsp;<code>False</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [12,5,7,23]
<strong>Output:</strong> true
<strong>Explanation:</strong> Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [29,6,10]
<strong>Output:</strong> true
<strong>Explanation:</strong> Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,6]
<strong>Output:</strong> false
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>1 &lt;= nums[i] &lt;= 10^9</code></li></ul>



<h2><strong>Solution: Math</strong></h2>



<p><a href="https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity">Bézout&#8217;s lemma</a>: b[1] * A[1] + b[2] * A[2] + &#8230;. + b[n] * A[n] = 1 &lt;==> gcd(A[1], A[2], &#8230;, A[n]) = 1 &lt;=> at least two numbers are co-prime</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isGoodArray(vector&lt;int&gt;&amp; nums) {
    int g = nums[0];
    for (int x : nums)
      g = gcd(g, x);    
    return g == 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1250-check-if-it-is-a-good-array/">花花酱 LeetCode 1250. Check If It Is a Good Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1250-check-if-it-is-a-good-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1201. Ugly Number III</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1201-ugly-number-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1201-ugly-number-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Sep 2019 08:34:14 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[lcm]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(logn)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5565</guid>

					<description><![CDATA[<p>Write a program to find the&#160;n-th ugly number. Ugly numbers are&#160;positive integers&#160;which are divisible by&#160;a&#160;or&#160;b&#160;or&#160;c. Example 1: Input: n = 3, a = 2, b&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1201-ugly-number-iii/">花花酱 LeetCode 1201. Ugly Number III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/gj4JevBj8-Y?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Write a program to find the&nbsp;<code>n</code>-th ugly number.</p>



<p>Ugly numbers are<strong>&nbsp;positive integers</strong>&nbsp;which are divisible by&nbsp;<code>a</code>&nbsp;<strong>or</strong>&nbsp;<code>b</code>&nbsp;<strong>or</strong>&nbsp;<code>c</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, a = 2, b = 3, c = 5
<strong>Output:</strong> 4
<strong>Explanation: </strong>The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, a = 2, b = 3, c = 4
<strong>Output:</strong> 6
<strong>Explanation: </strong>The ugly numbers are 2, 3, 4, 6, 8, 9, 12... The 4th is 6.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, a = 2, b = 11, c = 13
<strong>Output:</strong> 10
<strong>Explanation: </strong>The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1000000000, a = 2, b = 217983653, c = 336916467
<strong>Output:</strong> 1999999984
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n, a, b, c &lt;= 10^9</code></li><li><code>1 &lt;= a * b * c &lt;= 10^18</code></li><li>It&#8217;s guaranteed that the result will be in range&nbsp;<code>[1,&nbsp;2 * 10^9]</code></li></ul>



<h2><strong>Solution: Binary Search</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1201-ep270.png" alt="" class="wp-image-5582" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1201-ep270.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1201-ep270-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1201-ep270-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Number of ugly numbers that are &lt;= m are:</p>



<p>m / a + m / b + m / c &#8211; (m / LCM(a,b) + m / LCM(a, c) + m / LCM(b, c) + m / LCM(a, LCM(b, c))</p>



<p>Time complexity: O(logn)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int nthUglyNumber(int n, long a, long b, long c) {    
    long l = 1;
    long r = INT_MAX;
    long ab = lcm(a, b);
    long ac = lcm(a, c);
    long bc = lcm(b, c);
    long abc = lcm(a, bc);
    while (l &lt; r) {
      long m = l + (r - l) / 2;
      long k = m / a + m / b + m / c - m / ab - m / ac - m / bc + m / abc;      
      if (k &gt;= n) r = m;
      else l = m + 1;
    }
    return l;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1201-ugly-number-iii/">花花酱 LeetCode 1201. Ugly Number III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1201-ugly-number-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 914. X of a Kind in a Deck of Cards</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-914-x-of-a-kind-in-a-deck-of-cards/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-914-x-of-a-kind-in-a-deck-of-cards/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Sep 2018 08:02:20 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hashatable]]></category>
		<category><![CDATA[parition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4087</guid>

					<description><![CDATA[<p>Problem n a deck of cards, each card has an integer written on it. Return true if and only if you can choose X &#62;= 2 such that it is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-914-x-of-a-kind-in-a-deck-of-cards/">花花酱 LeetCode 914. X of a Kind in a Deck of Cards</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>n a deck of cards, each card has an integer written on it.</p>
<p>Return <code>true</code> if and only if you can choose <code>X &gt;= 2</code> such that it is possible to split the entire deck into 1 or more groups of cards, where:</p>
<ul>
<li>Each group has exactly <code>X</code> cards.</li>
<li>All the cards in each group have the same integer.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">[1,2,3,4,4,3,2,1]</span>
<strong>Output: </strong><span id="example-output-1">true
<strong>Explanation</strong>: Possible partition [1,1],[2,2],[3,3],[4,4]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">[1,1,1,2,2,2,3,3]</span>
<strong>Output: </strong><span id="example-output-2">false
</span><span id="example-output-1"><strong>Explanation</strong>: No possible partition.</span>
</pre>
<div>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">[1]</span>
<strong>Output: </strong><span id="example-output-3">false
</span><span id="example-output-1"><strong>Explanation</strong>: No possible partition.</span>
</pre>
<div>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-4-1">[1,1]</span>
<strong>Output: </strong><span id="example-output-4">true
</span><span id="example-output-1"><strong>Explanation</strong>: Possible partition [1,1]</span>
</pre>
<div>
<p><strong>Example 5:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-5-1">[1,1,2,2,2,2]</span>
<strong>Output: </strong><span id="example-output-5">true
</span><span id="example-output-1"><strong>Explanation</strong>: Possible partition [1,1],[2,2],[2,2]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= deck.length &lt;= 10000</code></li>
<li><code>0 &lt;= deck[i] &lt; 10000</code></li>
</ol>
<h1><strong>Solution 1: HashTable + Brute Force</strong></h1>
<p>Try all possible Xs. 2 ~ deck.size()</p>
<p>Time complexity: ~O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms
class Solution {
public:
  bool hasGroupsSizeX(vector&lt;int&gt;&amp; deck) {
    unordered_map&lt;int, int&gt; counts;
    for (int card : deck) ++counts[card];
    for (int i = 2; i &lt;= deck.size(); ++i) {
      if (deck.size() % i) continue;
      bool ok = true;
      for (const auto&amp; pair : counts)
        if (pair.second % i) {
          ok = false;
          break;
        }
      if (ok) return true;
    }
    return false;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: HashTable + GCD</strong></h1>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms
class Solution {
public:
  bool hasGroupsSizeX(vector&lt;int&gt;&amp; deck) {
    unordered_map&lt;int, int&gt; counts;
    for (int card : deck) ++counts[card];
    int X = deck.size();
    for (const auto&amp; p : counts) 
      X = __gcd(X, p.second);
    return X &gt;= 2;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Somebody
class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();
        for (int i=0; i&lt;deck.length; i++) {
            int curr = deck[i];
            if (map.containsKey(curr)) {
                map.put(curr, map.get(curr) + 1);
            } else {
                map.put(curr, 1);
            }
        }
        
        // O(nLogn)
        int gcd = 0;
        for(Integer key: map.keySet()) {
            gcd = findGCDOfTwoNumbers(map.get(key), gcd);
        }
        
        return gcd &gt;= 2;      
    }
    
    // O(Log n)
    public static int findGCDOfTwoNumbers (int a, int b) {
        if (b == 0) {
            return a;
        }
        return findGCDOfTwoNumbers(b, a%b);
    }
}</pre><p>&nbsp;</p>
<p></div></div></p>
<p><strong> </strong></p>
</div>
</div>
</div>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-914-x-of-a-kind-in-a-deck-of-cards/">花花酱 LeetCode 914. X of a Kind in a Deck of Cards</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-914-x-of-a-kind-in-a-deck-of-cards/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 592. Fraction Addition and Subtraction</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-592-fraction-addition-and-subtraction/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-592-fraction-addition-and-subtraction/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 07 Aug 2018 05:11:43 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[fraction]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3461</guid>

					<description><![CDATA[<p>Problem Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-592-fraction-addition-and-subtraction/">花花酱 LeetCode 592. Fraction Addition and Subtraction</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="question-description__3U1T">
<div>
<h1><strong>Problem</strong></h1>
<p>Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be <a href="https://en.wikipedia.org/wiki/Irreducible_fraction">irreducible fraction</a>. If your final result is an integer, say <code>2</code>, you need to change it to the format of fraction that has denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b>"-1/2+1/2"
<b>Output:</b> "0/1"
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b>"-1/2+1/2+1/3"
<b>Output:</b> "1/3"
</pre>
<p><b>Example 3:</b></p>
<pre class="crayon:false"><b>Input:</b>"1/3-1/2"
<b>Output:</b> "-1/6"
</pre>
<p><b>Example 4:</b></p>
<pre class="crayon:false"><b>Input:</b>"5/3+1/3"
<b>Output:</b> "2/1"
</pre>
<p><b>Note:</b></p>
<ol>
<li>The input string only contains <code>'0'</code> to <code>'9'</code>, <code>'/'</code>, <code>'+'</code> and <code>'-'</code>. So does the output.</li>
<li>Each fraction (input and output) has format <code>±numerator/denominator</code>. If the first input fraction or the output is positive, then <code>'+'</code> will be omitted.</li>
<li>The input only contains valid <b>irreducible fractions</b>, where the <b>numerator</b> and <b>denominator</b> of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.</li>
<li>The number of given fractions will be in the range [1,10].</li>
<li>The numerator and denominator of the <b>final result</b> are guaranteed to be valid and in the range of 32-bit int.</li>
</ol>
</div>
</div>
<h1><strong>Solution: Math</strong></h1>
<p>a/b+c/d = (a*d + b * c) / (b * d)</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string fractionAddition(string expression) {
    int a = 0;
    int b = 1;    
    int c;
    int d;
    char slash;
    istringstream in(expression);
    while (in &gt;&gt; c &gt;&gt; slash &gt;&gt; d) {
      a = a * d + b * c;
      b *= d;
      int gcd = abs(__gcd(a, b));
      a /= gcd;
      b /= gcd;      
    }
    return to_string(a) + "/" + to_string(b);
  }
};</pre><p></div><h2 class="tabtitle">C++/class</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Fraction {
public:
  Fraction(int a, int b): a_(a), b_(b) {}
  Fraction&amp; operator+=(const Fraction&amp; f) {
    a_ = a_ * f.b_ + b_ * f.a_;
    b_ = b_ * f.b_;
    int d = abs(__gcd(a_, b_));
    a_ /= d;
    b_ /= d;
    return *this;
  }
  
  string toString() {
    return to_string(a_) + "/" + to_string(b_);
  }
private:
  int a_; // hold the sign, e.g. can be +-.
  int b_; // always &gt; 0.
};

class Solution {
public:
    string fractionAddition(string expression) {
      Fraction f(0, 1);
      int a;
      int b;
      char op;
      istringstream in(expression);
      while (in &gt;&gt; a &gt;&gt; op &gt;&gt; b)
        f += Fraction(a, b);  
      return f.toString();
    }
};</pre><p></div></div></p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-592-fraction-addition-and-subtraction/">花花酱 LeetCode 592. Fraction Addition and Subtraction</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-592-fraction-addition-and-subtraction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 878. Nth Magical Number</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-878-nth-magical-number/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-878-nth-magical-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 05:15:21 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[lcm]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3359</guid>

					<description><![CDATA[<p>Problem A positive integer is magical if it is divisible by either A or B. Return the N-th magical number.  Since the answer may be very large, return it modulo 10^9 + 7. Example&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-878-nth-magical-number/">花花酱 LeetCode 878. Nth Magical Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>A positive integer is <em>magical</em> if it is divisible by either <span style="font-family: monospace;">A</span> or <span style="font-family: monospace;">B</span>.</p>
<p>Return the <span style="font-family: monospace;">N</span>-th magical number.  Since the answer may be very large, <strong>return it modulo </strong><code>10^9 + 7</code>.</p>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-1-1">1</span>, A = <span id="example-input-1-2">2</span>, B = <span id="example-input-1-3">3</span>
<strong>Output: </strong><span id="example-output-1">2</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-2-1">4</span>, A = <span id="example-input-2-2">2</span>, B = <span id="example-input-2-3">3</span>
<strong>Output: </strong><span id="example-output-2">6</span>
</pre>
<div>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-3-1">5</span>, A = <span id="example-input-3-2">2</span>, B = <span id="example-input-3-3">4</span>
<strong>Output: </strong><span id="example-output-3">10</span>
</pre>
<div>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-4-1">3</span>, A = <span id="example-input-4-2">6</span>, B = <span id="example-input-4-3">4</span>
<strong>Output: </strong><span id="example-output-4">8</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= N &lt;= 10^9</code></li>
<li><code>2 &lt;= A &lt;= 40000</code></li>
<li><code>2 &lt;= B &lt;= 40000</code></li>
</ol>
<h1><strong>Solution: Math + Binary Search</strong></h1>
<p>Let n denote the number of numbers &lt;= X that are divisible by either <span style="font-family: monospace;">A</span> or <span style="font-family: monospace;">B.</span></p>
<p>n = X / A + X / B &#8211; X / lcm(A, B) = X / A + X / B &#8211; X / (A * B / gcd(A, B))</p>
<p>Binary search for the smallest X such that n &gt;= N</p>
<p>Time complexity: O(log(1e9*4e5)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Solution {
public:
  int nthMagicalNumber(int N, int A, int B) {
    const int kMod = 1000000007;
    long l = 2;
    long r = static_cast&lt;long&gt;(1e9 * 4e5);
    int d = gcd(A, B);
    while (l &lt; r) {
      long m = (r - l) / 2 + l;
      if (m / A + m / B - m / (A * B / d) &lt; N)
        l = m + 1;
      else
        r = m;
    }
    return l % kMod;
  }
private:
  int gcd(int a, int b) {
    if (a % b == 0) return b;
    return gcd(b, a % b);
  }
};</pre><p>&nbsp;</p>
</div>
</div>
</div>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-878-nth-magical-number/">花花酱 LeetCode 878. Nth Magical Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-878-nth-magical-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
