★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:爲敢(WeiGanTechnologies)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-zgpvfkvi-ka.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Return the number of permutations of 1 to n
so that prime numbers are at prime indices (1-indexed.)git
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)github
Since the answer may be large, return the answer modulo 10^9 + 7
.微信
Example 1:spa
Input: n = 5 Output: 12 Explanation: 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.
Example 2:設計
Input: n = 100 Output: 682289015
Constraints:code
1 <= n <= 100
請你幫忙給從 1
到 n
的數設計排列方案,使得全部的「質數」都應該被放在「質數索引」(索引從 1 開始)上;你須要返回可能的方案總數。htm
讓咱們一塊兒來回顧一下「質數」:質數必定是大於 1 的,而且不能用兩個小於它的正整數的乘積來表示。blog
因爲答案可能會很大,因此請你返回答案 模 mod 10^9 + 7
以後的結果便可。索引
示例 1:
輸入:n = 5 輸出:12 解釋:舉個例子,[1,2,5,4,3] 是一個有效的排列,但 [5,2,3,4,1] 不是,由於在第二種狀況裏質數 5 被錯誤地放在索引爲 1 的位置上。
示例 2:
輸入:n = 100 輸出:682289015
提示:
1 <= n <= 100
1 class Solution { 2 private var count = 0 3 private let modulo: UInt64 = 1_000_000_000 + 7 4 5 func numPrimeArrangements(_ n: Int) -> Int { 6 var primeCount = 0 7 for i in 1 ... n { 8 if isPrime(i) { 9 primeCount += 1 10 } 11 } 12 13 14 let primePermutations = permutationCount(primeCount) 15 let compositePermutations = permutationCount(n - primeCount) 16 17 return Int((primePermutations * compositePermutations) % modulo) 18 } 19 20 private func isPrime(_ n: Int) -> Bool { 21 guard n > 1 else { return false } 22 if n == 2 { return true } 23 if n == 3 { return true } 24 for k in 2 ... Int(sqrt(Float(n))) { 25 if n % k == 0 { 26 return false 27 } 28 } 29 return true 30 } 31 32 private func permutationCount(_ n: Int) -> UInt64 { 33 guard n > 0 else { return 1 } 34 var count: UInt64 = 1 35 for i in 1 ... n { 36 count = ( count * UInt64(i) ) % modulo 37 } 38 return count 39 } 40 }
Runtime: 8 ms
1 class Solution { 2 func numPrimeArrangements(_ n: Int) -> Int { 3 var p:Set<Int> = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] 4 let MOD:Int = 1000000007 5 var ca:Int = 0 6 var cb:Int = 0 7 for i in 1...n 8 { 9 if p.contains(i) 10 { 11 ca += 1 12 } 13 else 14 { 15 cb += 1 16 } 17 } 18 var ans:Int = 1 19 if ca >= 1 20 { 21 for i in 1...ca 22 { 23 ans = ans * i % MOD 24 } 25 } 26 if cb >= 1 27 { 28 for i in 1...cb 29 { 30 ans = ans * i % MOD 31 } 32 } 33 return ans 34 } 35 }