Skip to content

Latest commit

 

History

History
74 lines (56 loc) · 1.63 KB

1175.md

File metadata and controls

74 lines (56 loc) · 1.63 KB

Prime Arrangements

题目

Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)

(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 10^9 + 7.

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 <= n <= 100

给定一个值n,[1,2,3...n]的全排列中有多少种排列满足一下条件: 1 质数在质数索引位置,非质数在非质数索引位置。

思路

计算出质数的数量n 非质数数量m, n*m即为答案。

代码

func numPrimeArrangements(n int) int {
    prime, notPrime := make([]int, 0), make([]int, 0)
    notPrime = append(notPrime, 1)
    for i := 2; i <= n; i++ {
        isPrime := true
        for j := 2; j <= i/2; j++ {
            if i != j && i % j == 0 {
                isPrime = false
                notPrime = append(notPrime, i)
                break
            }
        }
        if isPrime {
            prime = append(prime, i)
        }
    }
    //fmt.Println(prime, notPrime)
    l1 , l2 := len(prime), len(notPrime)
    res := 1
    for i := 1; i <= l1; i++ {
        res *= i
        if res > 1000000007 {
            res %= 1000000007
        }
    }
    for i := 1; i <= l2; i++ {
        res *= i
        if res > 1000000007 {
            res %= 1000000007
        }
    }
    return res
}