<?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>prime Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/prime/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/prime/</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>prime Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/prime/</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 1808. Maximize Number of Nice Divisors</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1808-maximize-number-of-nice-divisors/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1808-maximize-number-of-nice-divisors/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Mar 2021 05:49:16 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[factors]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8290</guid>

					<description><![CDATA[<p>You are given a positive integer&#160;primeFactors. You are asked to construct a positive integer&#160;n&#160;that satisfies the following conditions: The number of prime factors of&#160;n&#160;(not necessarily&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1808-maximize-number-of-nice-divisors/">花花酱 LeetCode 1808. Maximize Number of Nice 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>You are given a positive integer&nbsp;<code>primeFactors</code>. You are asked to construct a positive integer&nbsp;<code>n</code>&nbsp;that satisfies the following conditions:</p>



<ul><li>The number of prime factors of&nbsp;<code>n</code>&nbsp;(not necessarily distinct) is&nbsp;<strong>at most</strong>&nbsp;<code>primeFactors</code>.</li><li>The number of nice divisors of&nbsp;<code>n</code>&nbsp;is maximized. Note that a divisor of&nbsp;<code>n</code>&nbsp;is&nbsp;<strong>nice</strong>&nbsp;if it is divisible by every prime factor of&nbsp;<code>n</code>. For example, if&nbsp;<code>n = 12</code>, then its prime factors are&nbsp;<code>[2,2,3]</code>, then&nbsp;<code>6</code>&nbsp;and&nbsp;<code>12</code>&nbsp;are nice divisors, while&nbsp;<code>3</code>&nbsp;and&nbsp;<code>4</code>&nbsp;are not.</li></ul>



<p>Return&nbsp;<em>the number of nice divisors of</em>&nbsp;<code>n</code>. Since that number can be too large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p>Note that a prime number is a natural number greater than&nbsp;<code>1</code>&nbsp;that is not a product of two smaller natural numbers. The prime factors of a number&nbsp;<code>n</code>&nbsp;is a list of prime numbers such that their product equals&nbsp;<code>n</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> primeFactors = 5
<strong>Output:</strong> 6
<strong>Explanation:</strong> 200 is a valid value of n.
It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
There is not other value of n that has at most 5 prime factors and more nice divisors.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> primeFactors = 8
<strong>Output:</strong> 18
</pre>



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



<ul><li><code>1 &lt;= primeFactors &lt;= 10<sup>9</sup></code></li></ul>



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



<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 maxNiceDivisors(int n) {
    constexpr int kMod = 1e9 + 7;
    auto powm = [](long base, int exp) {
      long ans = 1;
      while (exp) {
        if (exp &amp; 1) ans = (ans * base) % kMod;
        base = (base * base) % kMod;
        exp &gt;&gt;= 1;
      }
      return ans;
    };
    
    if (n &lt;= 3) return n;
    switch (n % 3) {
      case 0: return powm(3, n / 3);
      case 1: return (powm(3, n / 3 - 1) * 4) % kMod;
      case 2: return (powm(3, n / 3) * 2) % kMod;
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1808-maximize-number-of-nice-divisors/">花花酱 LeetCode 1808. Maximize Number of Nice 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-1808-maximize-number-of-nice-divisors/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1735. Count Ways to Make Array With Product</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1735-count-ways-to-make-array-with-product/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1735-count-ways-to-make-array-with-product/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 Jan 2021 05:29:33 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[factor]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8017</guid>

					<description><![CDATA[<p>You are given a 2D integer array,&#160;queries. For each&#160;queries[i], where&#160;queries[i] = [ni, ki], find the number of different ways you can place positive integers into&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1735-count-ways-to-make-array-with-product/">花花酱 LeetCode 1735. Count Ways to Make Array With Product</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 a 2D integer array,&nbsp;<code>queries</code>. For each&nbsp;<code>queries[i]</code>, where&nbsp;<code>queries[i] = [n<sub>i</sub>, k<sub>i</sub>]</code>, find the number of different ways you can place positive integers into an array of size&nbsp;<code>n<sub>i</sub></code>&nbsp;such that the product of the integers is&nbsp;<code>k<sub>i</sub></code>. As the number of ways may be too large, the answer to the&nbsp;<code>i<sup>th</sup></code>&nbsp;query is the number of ways&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p>Return&nbsp;<em>an integer array&nbsp;</em><code>answer</code><em>&nbsp;where&nbsp;</em><code>answer.length == queries.length</code><em>, and&nbsp;</em><code>answer[i]</code><em>&nbsp;is the answer to the&nbsp;</em><code>i<sup>th</sup></code><em>&nbsp;query.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = [[2,6],[5,1],[73,660]]
<strong>Output:</strong> [4,1,50734910]
<strong>Explanation:</strong>&nbsp;Each query is independent.
[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].
[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].
[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 10<sup>9</sup> + 7 = 50734910.
</pre>



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



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



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



<ul><li><code>1 &lt;= queries.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= n<sub>i</sub>, k<sub>i</sub>&nbsp;&lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution1: DP</strong></h2>



<p>let dp(n, k) be the ways to have product k of array size n.<br>dp(n, k) = sum(dp(n &#8211; 1, i)) where i is a factor of k and i != k.<br>base case:<br>dp(0, 1) = 1, dp(0, *) = 0<br>dp(i, 1) = C(n, i)<br>e.g. <br>dp(2, 6) = dp(1, 1) + dp(1, 2) + dp(1, 3) <br>= 2 + 1 + 1 = 4<br>dp(4, 4) = dp(3, 1) + dp(3, 2) <br>= dp(3, 1) + dp(2, 1)<br>= 4 + 6 = 10<br></p>



<p>Time complexity: O(sum(k_i))?<br>Space complexity: O(sum(k_i))?</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; waysToFillArray(vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    constexpr int kMod = 1e9 + 7;
    int n = 0;
    unordered_map&lt;int, int&gt; c, dp;
    function&lt;int(int, int)&gt; cnk = [&amp;](int n, int k) {
      if (k &gt; n) return 0;
      if (k == 0 || k == n) return 1;      
      int&amp; ans = c[(n &lt;&lt; 16) | k];
      if (!ans) ans = (cnk(n - 1, k - 1) + cnk(n - 1, k)) % kMod; 
      return ans;      
    };
    
    function&lt;int(int, int)&gt; dfs = [&amp;](int s, int k) -&gt; int {
      if (s == 0) return k == 1;
      if (k == 1) return cnk(n, s);
      int&amp; ans = dp[(s &lt;&lt; 16) | k];
      if (ans) return ans;      
      for (int i = 1; i * i &lt;= k; ++i) {
        if (k % i) continue;
        if (i != 1) 
          ans = (ans + dfs(s - 1, k / i)) % kMod;
        if (i * i != k)
          ans = (ans + dfs(s - 1, i)) % kMod;
      }
      return ans;
    };
    
    vector&lt;int&gt; ans;
    for (const auto&amp; q : queries) {
      dp.clear();
      n = q[0];
      ans.push_back(dfs(n, q[1]));
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1735-count-ways-to-make-array-with-product/">花花酱 LeetCode 1735. Count Ways to Make Array With Product</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/dynamic-programming/leetcode-1735-count-ways-to-make-array-with-product/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1175. Prime Arrangements</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Sep 2019 05:10:02 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5511</guid>

					<description><![CDATA[<p>Return the number of permutations of 1 to&#160;n&#160;so that prime numbers are at prime indices (1-indexed.) (Recall that an integer&#160;is prime if and only if&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/">花花酱 LeetCode 1175. Prime Arrangements</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>Return the number of permutations of 1 to&nbsp;<code>n</code>&nbsp;so that prime numbers are at prime indices (1-indexed.)</p>



<p><em>(Recall that an integer&nbsp;is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers&nbsp;both smaller than it.)</em></p>



<p>Since the answer may be large, return the answer&nbsp;<strong>modulo&nbsp;<code>10^9 + 7</code></strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5
<strong>Output:</strong> 12
<strong>Explanation:</strong> For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 100
<strong>Output:</strong> 682289015
</pre>



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



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



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



<p>Count the number of primes in range [1, n], assuming there are p primes and n &#8211; p non-primes, we can permute each group separately. <br>ans = p!  * (n &#8211; p)!</p>



<p>Time complexity: O(nsqrt(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 numPrimeArrangements(int n) {
    const int kMod = 1e9 + 7;
    int p = 0;
    for (int i = 1; i &lt;= n; ++i)
      p += isPrime(i);
    long ans = 1;
    for (int i = 1; i &lt;= p; ++i)
      ans = (ans * i) % kMod;
    for (int i = 1; i &lt;= n - p; ++i)
      ans = (ans * i) % kMod;
    return ans;
  }
private:
  bool isPrime(int x) {
    if (x &lt; 2) return false;
    if (x == 2) return true;
    for (int i = 2; i &lt;= sqrt(x); ++i)
      if (x % i == 0) return false;
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/">花花酱 LeetCode 1175. Prime Arrangements</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-1175-prime-arrangements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 313. Super Ugly Number</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-313-super-ugly-number/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-313-super-ugly-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 03 Jan 2019 04:16:58 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prime]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4590</guid>

					<description><![CDATA[<p>Write a program to find the&#160;nth&#160;super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list&#160;primes&#160;of size&#160;k.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-313-super-ugly-number/">花花酱 LeetCode 313. Super Ugly 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[
<p>Write a program to find the&nbsp;<code>n<sup>th</sup></code>&nbsp;super ugly number.</p>



<p>Super ugly numbers are positive numbers whose all prime factors are in the given prime list&nbsp;<code>primes</code>&nbsp;of size&nbsp;<code>k</code>.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong> n = 12, <code>primes</code> = <code>[2,7,13,19]</code> <br><strong>Output:</strong> 32  <br><strong>Explanation: </strong><code>[1,2,4,7,8,13,14,16,19,26,28,32] </code>is the sequence of the first 12               super ugly numbers given <code>primes</code> = <code>[2,7,13,19]</code> of size 4.</pre>



<p><strong>Note:</strong></p>



<ul><li><code>1</code>&nbsp;is a super ugly number for any given&nbsp;<code>primes</code>.</li><li>The given numbers in&nbsp;<code>primes</code>&nbsp;are in ascending order.</li><li>0 &lt;&nbsp;<code>k</code>&nbsp;≤ 100, 0 &lt;&nbsp;<code>n</code>&nbsp;≤ 10<sup>6</sup>, 0 &lt;&nbsp;<code>primes[i]</code>&nbsp;&lt; 1000.</li><li>The n<sup>th</sup>&nbsp;super ugly number is guaranteed to fit in a 32-bit signed integer.</li></ul>



<h2><strong>Solution 1: Set</strong></h2>



<p>Maintain an ordered set of super ugly numbers, each time extract the smallest one, and multiply it with all primes and insert the new number into set.</p>



<p>Time complexity: O(n*k*logn)<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, running time: 484 ms
class Solution {
public:
  int nthSuperUglyNumber(int n, vector&lt;int&gt;&amp; primes) {
    if (n == 1) return 1;
    set&lt;int&gt; q{begin(primes), end(primes)};        
    for (int i = 0; i &lt; n - 2; ++i) {      
      auto it = begin(q);
      int t = *it;
      q.erase(it);
      for (int p : primes) {
        if (INT_MAX / t &lt; p) continue;        
        q.insert(p * t);
      }
      
    }
    return *begin(q);
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Priority Queue</strong></h2>



<p>Time complexity: O(nlogn)<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, 40 ms
struct Node {
  int num;
  int index;
  int prime;
  
  bool operator&gt;(const Node&amp; o) const {
    if (this-&gt;num == o.num) return this-&gt;index &gt; o.index;
    return this-&gt;num &gt; o.num;
  }
};

class Solution {
public:
  int nthSuperUglyNumber(int n, vector&lt;int&gt;&amp; primes) {
    if (n == 1) return 1;
    vector&lt;int&gt; nums(n, 1);
    priority_queue&lt;Node, vector&lt;Node&gt;, greater&lt;Node&gt;&gt; q;
    for (int p : primes)
      q.push({p, 1, p});
    for (int i = 1; i &lt; n; ++i) {
      nums[i] = q.top().num;
      while (nums[i] == q.top().num) {
        Node node = std::move(q.top()); q.pop();
        node.num = nums[node.index++] * node.prime;
        q.push(std::move(node));
      }
    }    
    return nums.back();
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-313-super-ugly-number/">花花酱 LeetCode 313. Super Ugly 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-313-super-ugly-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 867. Prime Palindrome</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-867-prime-palindrome/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-867-prime-palindrome/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Jul 2018 08:23:09 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3013</guid>

					<description><![CDATA[<p>Problem Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it&#8217;s only divisors are 1 and itself, and it is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-867-prime-palindrome/">花花酱 LeetCode 867. Prime Palindrome</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>Find the smallest prime palindrome greater than or equal to <code>N</code>.</p>
<p>Recall that a number is <em>prime</em> if it&#8217;s only divisors are 1 and itself, and it is greater than 1.</p>
<p>For example, 2,3,5,7,11 and 13 are primes.</p>
<p>Recall that a number is a <em>palindrome</em> if it reads the same from left to right as it does from right to left.</p>
<p>For example, 12321 is a palindrome.</p>
<p>&nbsp;</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">6</span>
<strong>Output: </strong><span id="example-output-1">7</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">8</span>
<strong>Output: </strong><span id="example-output-2">11</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">13</span>
<strong>Output: </strong><span id="example-output-3">101</span></pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= N &lt;= 10^8</code></li>
<li>The answer is guaranteed to exist and be less than <code>2 * 10^8</code>.</li>
</ul>
<h1><strong>Solution: Math</strong></h1>
<p>All odd digits palindromes have a factor 11, they are not prime except 11 itself.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  int primePalindrome(int N) {
    if (N &lt;= 2) return 2;
    if (N % 2 == 0) ++N;
    while (true) {      
      if (reverse(N) == N &amp;&amp; isPrime(N)) 
        return N;
      N += 2;
      if (N &gt; 11 &amp; (int)log10(N) % 2 == 1)
        // 13 -&gt; 101
        // 1001 -&gt; 10001                
        N = pow(10, (int)log10(N) + 1) + 1;
    }
    return -1;
  }
private:
  int reverse(int n) {
    int r = 0;
    while (n) {
      r = 10 * r + n % 10;
      n /= 10;
    }
    return r;
  }
  
  bool isPrime(int n) {
    if (n &lt;= 1) return false;
    for (int i = 2; i &lt;= sqrt(n); ++i)
      if (n % i == 0) return false;
    return true;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-867-prime-palindrome/">花花酱 LeetCode 867. Prime Palindrome</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-867-prime-palindrome/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 18 Jan 2018 06:08:40 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1636</guid>

					<description><![CDATA[<p>题目大意：求给定范围内，数的二进制形式中1的个数为素数个的数字的个数。 Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation. (Recall&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/">花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</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/KVKeyehcUuU?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：求给定范围内，数的二进制形式中1的个数为素数个的数字的个数。</p>
<p>Given two integers <code>L</code> and <code>R</code>, find the count of numbers in the range <code>[L, R]</code> (inclusive) having a prime number of set bits in their binary representation.</p>
<p>(Recall that the number of set bits an integer has is the number of <code>1</code>s present when written in binary. For example, <code>21</code> written in binary is <code>10101</code> which has 3 set bits. Also, 1 is not a prime.)</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: L = 6, R = 10
Output: 4
Explanation:
6 -&gt; 110 (2 set bits, 2 is prime)
7 -&gt; 111 (3 set bits, 3 is prime)
9 -&gt; 1001 (2 set bits , 2 is prime)
10-&gt;1010 (2 set bits , 2 is prime)</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: L = 10, R = 15
Output: 5
Explanation:
10 -&gt; 1010 (2 set bits, 2 is prime)
11 -&gt; 1011 (3 set bits, 3 is prime)
12 -&gt; 1100 (2 set bits, 2 is prime)
13 -&gt; 1101 (3 set bits, 3 is prime)
14 -&gt; 1110 (3 set bits, 3 is prime)
15 -&gt; 1111 (4 set bits, 4 is not prime)</pre><p><b>Note:</b></p>
<ol>
<li><code>L, R</code> will be integers <code>L &lt;= R</code> in the range <code>[1, 10^6]</code>.</li>
<li><code>R - L</code> will be at most 10000.</li>
</ol>
<p><strong>Solution 1: Brute Force</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 22 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (isPrime(bits(n))) ++ans;
    return ans;
  }
private:
  bool isPrime(int n) {
    if (n &lt;= 1) return false;
    if (n == 2) return true;      
    for (int i = 2; i &lt;= sqrt(n); ++i)
      if (n % i == 0) return false;
    return true;
  }
  
  int bits(int n) {
    int s = 0;
    while (n) {
      s += n &amp; 1;
      n &gt;&gt;= 1;
    }        
    return s;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    set&lt;int&gt; primes{2, 3, 5, 7, 11, 13, 17, 19};
    for (int n = L; n &lt;= R; ++n)
      if (primes.count(__builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p>&nbsp;</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 30 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    unordered_set&lt;int&gt; primes{2, 3, 5, 7, 11, 13, 17, 19};
    for (int n = L; n &lt;= R; ++n)
      if (primes.count(__builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    vector&lt;int&gt; p(20, 0);
    p[2] = p[3] = p[5] = p[7] = p[11] = p[13] = p[17] = p[19] = 1;
    for (int n = L; n &lt;= R; ++n)
      if (p[__builtin_popcountll(n)]) ++ans;
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    constexpr int magic = 665772;
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (magic &amp; (1 &lt;&lt; __builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 39 ms
class Solution {
  public int countPrimeSetBits(int L, int R) {
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (isPrime(bits(n))) ++ans;
    return ans;
  }
  
  private boolean isPrime(int n) {
    if (n &lt;= 1) return false;
    if (n == 2) return true;      
    for (int i = 2; i &lt;= (int)Math.sqrt(n); ++i)
      if (n % i == 0) return false;
    return true;
  }
  
  private int bits(int n) {
    int s = 0;
    while (n != 0) {
      s += n &amp; 1;
      n &gt;&gt;= 1;
    }        
    return s;
  }
}</pre><p>Python2</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1618 ms
"""
class Solution(object):
  def countPrimeSetBits(self, L, R):
    def isPrime(n):
      if n &lt;= 1: return False
      if n == 2: return True
      for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0: return False
      return True

    def bits(n):
      s = 0
      while n != 0:
        s += n &amp; 1
        n &gt;&gt;= 1
      return s

    ans = 0
    for n in range(L, R + 1):
      if isPrime(bits(n)): ans += 1
    return ans</pre><p>Python2</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1163 ms
"""
class Solution(object):
  def countPrimeSetBits(self, L, R):
    def bits(n):
      s = 0
      while n != 0:
        s += n &amp; 1
        n &gt;&gt;= 1
      return s
    
    primes = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31])

    ans = 0
    for n in range(L, R + 1):
      if bits(n) in primes: ans += 1
    return ans</pre><p></p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 667 ms
"""
class Solution(object):   
  def countPrimeSetBits(self, L, R):
    def bits(n):
      s = 0
      while n != 0:
        n &amp;= n - 1;
        s += 1
      return s
        
    ans = 0
    while L &lt;= R:
      if (665772 &gt;&gt; bits(L)) &amp; 1 &gt; 0: ans += 1
      L += 1

    return ans</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/">花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</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/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/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-663a350891f17685610571/]&#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>
