zoukankan      html  css  js  c++  java
  • 【leetcode】1175. 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~n这个区间有几个素数。假设素数有x个,x个素数占据x的位置,其排列方式的总和是x!;同理非素数有(n-x)个,那么这些非素数的排列方式就有(n-x)!个,两者的乘积即为最终的答案。

    代码如下:

    class Solution(object):
        def numPrimeArrangements(self, n):
            """
            :type n: int
            :rtype: int
            """
            prime = [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]
            import bisect
            prime_count = bisect.bisect_right(prime,n)
            no_prime_count = n - prime_count
            def calc(num):
                factorial = 1
                for i in range(1, num + 1):
                    factorial = factorial * i
                return factorial
    
            total = calc(prime_count) * calc(no_prime_count)
            return total % (10**9 + 7)
  • 相关阅读:
    Linux环境变量$PATH
    grep
    echo命令
    ip命令
    浅析Linux下的/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc文件
    shell脚本4种执行方式
    /proc路径
    tr命令
    Linux命令cut
    前端论坛网站知识
  • 原文地址:https://www.cnblogs.com/seyjs/p/11475209.html
Copyright © 2011-2022 走看看