在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Return the number of permutations of 1 to (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.) Since the answer may be large, return the answer modulo
Example 1: 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:
请你帮忙给从 让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。 由于答案可能会很大,所以请你返回答案 模 mod
示例 1: 输入:n = 5 输出:12 解释:举个例子,[1,2,5,4,3] 是一个有效的排列,但 [5,2,3,4,1] 不是,因为在第二种情况里质数 5 被错误地放在索引为 1 的位置上。 示例 2: 输入:n = 100 输出:682289015
提示:
0ms
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 Memory Usage: 20.9 MB
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 }
|
请发表评论