<?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>sqrt Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/sqrt/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/sqrt/</link>
	<description></description>
	<lastBuildDate>Sat, 01 Jan 2022 06:55:45 +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>sqrt Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/sqrt/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 1952. Three Divisors</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1952-three-divisors/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1952-three-divisors/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 20:55:01 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[divisor]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9317</guid>

					<description><![CDATA[<p>Given an integer&#160;n, return&#160;true&#160;if&#160;n&#160;has&#160;exactly three positive divisors. Otherwise, return&#160;false. An integer&#160;m&#160;is a&#160;divisor&#160;of&#160;n&#160;if there exists an integer&#160;k&#160;such that&#160;n = k * m. Example 1: Input: n&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1952-three-divisors/">花花酱 LeetCode 1952. Three Divisors</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&nbsp;<code>true</code><em>&nbsp;if&nbsp;</em><code>n</code><em>&nbsp;has&nbsp;<strong>exactly three positive divisors</strong>. Otherwise, return&nbsp;</em><code>false</code>.</p>



<p>An integer&nbsp;<code>m</code>&nbsp;is a&nbsp;<strong>divisor</strong>&nbsp;of&nbsp;<code>n</code>&nbsp;if there exists an integer&nbsp;<code>k</code>&nbsp;such that&nbsp;<code>n = k * m</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> false
<strong>Explantion:</strong> 2 has only two divisors: 1 and 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4
<strong>Output:</strong> true
<strong>Explantion:</strong> 4 has three divisors: 1, 2, and 4.
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Enumerate divisors.</strong></h2>



<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 isThree(int n) {
    int c = 0;
    for (int i = 1; i &lt;= n; ++i)
      if (n % i == 0) ++c;        
    return c == 3;
  }
};</pre>
</div></div>



<h2><strong>Optimization</strong></h2>



<p>Only need to enumerate divisors up to sqrt(n). Special handle for the d * d == n case.</p>



<p>Time complexity: O(sqrt(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 isThree(int n) {
    int c = 0;
    for (int i = 1; i &lt;= sqrt(n); ++i)
      if (n % i == 0)
        c += 1 + (i * i != n);
    return c == 3;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1952-three-divisors/">花花酱 LeetCode 1952. Three Divisors</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-1952-three-divisors/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1390. Four Divisors</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1390-four-divisors/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1390-four-divisors/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Mar 2020 21:06:57 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[divisor]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6539</guid>

					<description><![CDATA[<p>Given an integer array&#160;nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1390-four-divisors/">花花酱 LeetCode 1390. Four Divisors</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 the sum of divisors of the integers in that array that have exactly four divisors.</p>



<p>If there is no such integer in the array, return&nbsp;<code>0</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [21,4,7]
<strong>Output:</strong> 32
<strong>Explanation:</strong>
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
</pre>



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



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



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



<p>If a number is a perfect square (e.g. 9 = 3 * 3), it will have odd number of divisors. (9: 1, 3, 9).</p>



<p>Time complexity: O(sum(sqrt(num_i))<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 sumFourDivisors(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    for (int n : nums) {
      int r = sqrt(n);
      if (n &lt;= 4 || r * r == n) continue;
      int count = 2;
      int sum = 1 + n;
      for (int d = 2; d &lt;= r; ++d)
        if (n % d == 0) {
          count += 2;
          sum += n / d + d;
        }      
      if (count == 4) ans += sum;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1390-four-divisors/">花花酱 LeetCode 1390. Four Divisors</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-1390-four-divisors/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1362. Closest Divisors</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1362-closest-divisors/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1362-closest-divisors/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Feb 2020 20:00:46 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(sqrt(n))]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6373</guid>

					<description><![CDATA[<p>Given an integer&#160;num, find the closest two integers in absolute difference whose product equals&#160;num + 1&#160;or&#160;num + 2. Return the two integers in any order.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1362-closest-divisors/">花花酱 LeetCode 1362. Closest Divisors</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>num</code>, find the closest two integers in absolute difference whose product equals&nbsp;<code>num + 1</code>&nbsp;or&nbsp;<code>num + 2</code>.</p>



<p>Return the two integers in any order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 8
<strong>Output:</strong> [3,3]
<strong>Explanation:</strong> For num + 1 = 9, the closest divisors are 3 &amp; 3, for num + 2 = 10, the closest divisors are 2 &amp; 5, hence 3 &amp; 3 is chosen.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 123
<strong>Output:</strong> [5,25]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 999
<strong>Output:</strong> [40,25]
</pre>



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



<ul><li><code>1 &lt;= num &lt;= 10^9</code></li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Time complexity: O(sqrt(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:
  vector&lt;int&gt; closestDivisors(int num) {
    auto divisors = [](int n) {
      for (int i = sqrt(n); i &gt;= 2; --i)
        if (n % i == 0) return vector&lt;int&gt;{i, n / i};
      return vector&lt;int&gt;{1, n};
    };
    
    auto ans1 = divisors(num + 1);
    auto ans2 = divisors(num + 2);
    return ans1[1] - ans1[0] &lt; ans2[1] - ans2[0] ? ans1 : ans2;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def closestDivisors(self, num: int) -&gt; List[int]:
    def divisors(n: int) -&gt; List[int]:
      for i in range(int(math.sqrt(n)), 1, -1):
        if n % i == 0: return [i, n // i]
      return [1, n]
    
    a1, a2 = divisors(num + 1), divisors(num + 2)
    return a1 if a1[1] - a1[0] &lt; a2[1] - a2[0] else a2</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1362-closest-divisors/">花花酱 LeetCode 1362. Closest Divisors</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-1362-closest-divisors/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 633. Sum of Square Numbers</title>
		<link>https://zxi.mytechroad.com/blog/uncategorized/leetcode-633-sum-of-square-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/uncategorized/leetcode-633-sum-of-square-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 22 Aug 2018 15:22:29 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3660</guid>

					<description><![CDATA[<p>Problem Given a non-negative integer c, your task is to decide whether there&#8217;re two integers a and b such that a2 + b2 = c. Example 1: Input: 5 Output: True Explanation:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-633-sum-of-square-numbers/">花花酱 LeetCode 633. Sum of Square Numbers</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><iframe width="500" height="375" src="https://www.youtube.com/embed/2tiZMMTt-CQ?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given a non-negative integer <code>c</code>, your task is to decide whether there&#8217;re two integers <code>a</code> and <code>b</code> such that a<sup>2</sup> + b<sup>2</sup> = c.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> 5
<b>Output:</b> True
<b>Explanation:</b> 1 * 1 + 2 * 2 = 5
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> 3
<b>Output:</b> False
</pre>
<h1><strong>Solution: Math</strong></h1>
<p>Time complexity: O(sqrt(c))</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  bool judgeSquareSum(int c) {
    int m = sqrt(c);
    for (int a = 0; a &lt;= m; ++a) {
      int b = round(sqrt(c - a * a));
      if (a * a + b * b == c) return true;
    }
    return false;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-633-sum-of-square-numbers/">花花酱 LeetCode 633. Sum of Square Numbers</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/uncategorized/leetcode-633-sum-of-square-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 492. Construct the Rectangle</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-492-construct-the-rectangle/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-492-construct-the-rectangle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 02 Jun 2018 20:00:10 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2883</guid>

					<description><![CDATA[<p>Problem For a web developer, it is very important to know how to design a web page&#8217;s size. So, given a specific rectangular web page’s&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-492-construct-the-rectangle/">花花酱 LeetCode 492. Construct the Rectangle</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>Problem</h1>
<p>For a web developer, it is very important to know how to design a web page&#8217;s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>
<pre class="crayon:false">1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L &gt;= W.

3. The difference between length L and width W should be as small as possible.
</pre>
<p>You need to output the length L and the width W of the web page you designed in sequence.</p>
<p><b>Example:</b></p>
<pre class="crayon:false "><b>Input:</b> 4
<b>Output:</b> [2, 2]
<b>Explanation:</b> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
</pre>
<p><b>Note:</b></p>
<ol>
<li>The given area won&#8217;t exceed 10,000,000 and is a positive integer</li>
<li>The web page&#8217;s width and length you designed must be positive integers.</li>
</ol>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(sqrt(n))</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 3 ms (&lt;98.48%)
class Solution {
public:
  vector&lt;int&gt; constructRectangle(int area) {    
    for (int i = sqrt(area); i &gt;= 1; --i)
      if (area % i == 0) return {area / i, i};    
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-492-construct-the-rectangle/">花花酱 LeetCode 492. Construct the Rectangle</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-492-construct-the-rectangle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 507. Perfect Number</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-507-perfect-number/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-507-perfect-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 23 Mar 2018 05:23:54 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2308</guid>

					<description><![CDATA[<p>Problem 题目大意：判断一个数的因数和是不是等于它本身。 https://leetcode.com/problems/perfect-number/description/ We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. Now, given an integer n, write&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-507-perfect-number/">花花酱 LeetCode 507. Perfect 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>题目大意：判断一个数的因数和是不是等于它本身。</p>
<p><a href="https://leetcode.com/problems/perfect-number/description/">https://leetcode.com/problems/perfect-number/description/</a></p>
<p>We define the Perfect Number is a <b>positive</b> integer that is equal to the sum of all its <b>positive</b> divisors except itself.</p>
<p>Now, given an <b>integer</b> n, write a function that returns true when it is a perfect number and false when it is not.</p>
<p><b>Example:</b></p>
<pre class="crayon:false "><b>Input:</b> 28
<b>Output:</b> True
<b>Explanation:</b> 28 = 1 + 2 + 4 + 7 + 14
</pre>
<p><b>Note:</b> The input number <b>n</b> will not exceed 100,000,000. (1e8)</p>
<h1><strong>Solution: Brute Force</strong></h1>
<p>Try allnumbers from 1 to n &#8211; 1.</p>
<p>Time complexity: O(n) TLE for prime numbers</p>
<p>Space complexity: O(1)</p>
<h1><strong>Solution: Math</strong></h1>
<p>Try all numbers from 2 to sqrt(n).</p>
<p>If number i is a divisor of n then n/i is another one.</p>
<p>Be careful about the case when i == n/i, only one should be added to the sum.</p>
<p>Time complexity: O(sqrt(n))</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
public:
  bool checkPerfectNumber(int num) {
    if (num &lt;= 1) return false;    
    int sum = 1;
    for (int i = 2; i &lt;= sqrt(num); ++i)
      if (num % i == 0) sum += i + ((i == num / i) ? 0 : num / i);   
    return sum == num;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-507-perfect-number/">花花酱 LeetCode 507. Perfect 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-507-perfect-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode. 69 Sqrt(x)</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 17 Jan 2018 02:41:12 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[newton]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1613</guid>

					<description><![CDATA[<p>题目大意：让你实现开根号函数，只需要返回整数部分。 Problem: Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. Example 1: [crayon-663c7ecdef5cc372156521/] Example 2: [crayon-663c7ecdef5cf913612888/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/">花花酱 LeetCode. 69 Sqrt(x)</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><iframe width="500" height="375" src="https://www.youtube.com/embed/_K4f9I11hYI?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：让你实现开根号函数，只需要返回整数部分。</p>
<p><strong>Problem:</strong></p>
<p>Implement <code>int sqrt(int x)</code>.</p>
<p>Compute and return the square root of <i>x</i>.</p>
<p><b>x</b> is guaranteed to be a non-negative integer.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: 4
Output: 2</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842...</pre><p>&nbsp;</p>
<p><img class="alignnone size-full wp-image-1624" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1628" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"> </ins></p>
<h1><strong>Solution 1: Brute force</strong></h1>
<p>Time complexity: sqrt(x)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 40 ms
class Solution {
public:
  int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (long long s = 1; s &lt;= x; ++s)
      if (s * s &gt; x) return s - 1;
    return -1;
  }
};</pre><p></div><h2 class="tabtitle">C++ div</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 162 ms
class Solution {
public:
  int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (int s = 1; s &lt;= x; ++s)
      if (s &gt; x / s) return s - 1;
    return -1;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 71 ms
class Solution {
  public int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (long s = 1; s &lt;= x; ++s)
      if (s * s &gt; x) return (int)s - 1;
    return -1;
  }
}</pre><p></div><h2 class="tabtitle">Python3 TLE</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
TLE: 602 / 1017 test cases passed.
"""
class Solution:
  def mySqrt(self, x):
    if x &lt;= 1: return x
    s = 1
    while True:
      if s*s &gt; x: return s - 1
      s += 1
    return -1</pre><p></div></div></p>
<h1><strong>Solution 2: Binary search</strong></h1>
<p>Time complexity: O(logn)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  int mySqrt(int x) {      
    long l = 1;
    long r = static_cast&lt;long&gt;(x) + 1;
    while (l &lt; r) {
      long m = l + (r - l) / 2;
      if (m * m &gt; x) { 
        r = m;
      } else {
        l = m + 1;
      }
    }
    // l: smallest number such that l * l &gt; x
    return l - 1;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 47 ms
class Solution {
  public int mySqrt(int x) {      
    int l = 1;
    int r = x;
    while (l &lt;= r) {
      int m = l + (r - l) / 2;
      if (m &gt; x / m) {
        r = m - 1;
      } else {
        l = m + 1;
      }
    }
    return r;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 119 ms
"""
class Solution:
  def mySqrt(self, a):
    l = 1
    r = a
    while l &lt;= r:
      m = l + (r - l) // 2
      if m * m &gt; a:
        r = m - 1
      else:
        l = m + 1
    return r;</pre><p></div></div></p>
<h1><strong>Solution 3: Newton&#8217;s method</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ / float</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
public:
    int mySqrt(int a) {
      constexpr double epsilon = 1e-2;
      double x = a;
      while (x * x - a &gt; epsilon) {
        x = (x + a / x) / 2.0;
      }
      return x;
    }
};</pre><p></div><h2 class="tabtitle">C++ / int</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 27 ms
class Solution {
public:
  int mySqrt(int a) {
    // f(x) = x^2 - a, find root of f(x)
    // Newton's method
    // f'(x) = 2x
    // x' = x - f(x) / f'(x) = x - (1/2*x - a/(2*x))
    //    = (x + a / x) / 2
    int x = a;
    while (x &gt; a / x)
      x = (x + a / x) / 2;
    return x;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 44 ms
class Solution {
  public int mySqrt(int a) {    
    long x = a;
    while (x * x &gt; a)
      x = (x + a / x) / 2;    
    return (int)x;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 100 ms
"""
class Solution:
  def mySqrt(self, a):
    x = a
    while x * x &gt; a:
      x = (x + a // x) // 2
    return x</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/">花花酱 LeetCode. 69 Sqrt(x)</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-69-sqrtx/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 204. Count Primes</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-204-count-primes/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-204-count-primes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 09 Sep 2017 08:39:47 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[prime]]></category>
		<category><![CDATA[sieve]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=168</guid>

					<description><![CDATA[<p>Problem: Count the number of prime numbers less than a non-negative number, n. Idea: Sieve of Eratosthenes Time Complexity: O(nloglogn) Space Complexity: O(n) Solution: C++ [crayon-663c7ecdef84c662281154/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-204-count-primes/">花花酱 LeetCode 204. Count Primes</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><iframe width="500" height="375" src="https://www.youtube.com/embed/Kwo2jkHOyPY?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Count the number of prime numbers less than a non-negative number, <b><i>n</i></b>.</p>
<p><strong>Idea:</strong></p>
<p><a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a></p>
<p><strong>Time Complexity:</strong></p>
<p>O(nloglogn)</p>
<p><strong>Space Complexity:</strong></p>
<p>O(n)</p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    int countPrimes(int n) {
        if (n &lt; 3) return 0;
        
        vector&lt;unsigned char&gt; f(n, 1);
        f[0] = f[1] = 0;
        for(long i=2;i&lt;=sqrt(n);++i) {
            if(!f[i]) continue;
            for(long j=i*i;j&lt;n;j+=i)
                f[j] = 0;
        }
        
        int ans = accumulate(f.begin(), f.end(), 0);
        return ans;
    }
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 ms
class Solution {
  public int countPrimes(int n) {
    int ans = 0;
    boolean[] isPrime = new boolean[n + 1];
    Arrays.fill(isPrime, true);
    isPrime[0] = false;
    if (n &gt; 0) isPrime[1] = false;
    for (int i = 2; i &lt; n; ++i) {
      if (!isPrime[i]) continue;
      ++ans;
      for (int j = 2 * i; j &lt; n; j += i)
        isPrime[j] = false;
    }
    return ans;
  }
}</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 800 ms
"""
class Solution:
  def countPrimes(self, n):
    if n &lt; 3: return 0
    isPrime = [True] * (n + 1)
    isPrime[0] = False
    isPrime[1] = False
    ans = 0
    for i in range(2, n):
      if not isPrime[i]: continue
      ans += 1
      for j in range(2 * i, n, i):
        isPrime[j] = False
    return ans</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-204-count-primes/">花花酱 LeetCode 204. Count Primes</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-204-count-primes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
