코드로 우주평화

Primorial Of a Number 본문

나는 이렇게 학습한다/Algorithm & SQL

Primorial Of a Number

daco2020 2022. 3. 18. 13:59
반응형

Description:

Definition (Primorial Of a Number)

Is similar to factorial of a number, In primorial, not all the natural numbers get multiplied, only prime numbers are multiplied to calculate the primorial of a number. It's denoted with P# and it is the product of the first n prime numbers.


Task

Given a number N , calculate its primorial.

 

 

Notes

  • Only positive numbers will be passed (N > 0) .

 

Input >> Output Examples:

1- numPrimorial (3) ==> return (30)

 

Explanation:

Since the passed number is (3) ,Then the primorial should obtained by multiplying 2 * 3 * 5 = 30 .

Mathematically written as , P3# = 30 .


2- numPrimorial (5) ==> return (2310)

 

Explanation:

Since the passed number is (5) ,Then the primorial should obtained by multiplying 2 * 3 * 5 * 7 * 11 = 2310 .

Mathematically written as , P5# = 2310 .


3- numPrimorial (6) ==> return (30030)

 

Explanation:

Since the passed number is (6) ,Then the primorial should obtained by multiplying 2 * 3 * 5 * 7 * 11 * 13 = 30030 .

Mathematically written as , P6# = 30030 .

 

 

Solution:

1. Create an array of 'n' or more prime numbers.
2. Multiplies and returns 'n' prime numbers.

 

# Sieve of Eratosthenes
def arr_primenumber(x): 
    a = [False,False] + [True]*(x-1)
    primes=[]
    for i in range(2,x+1):
        if a[i]:
            primes.append(i)
            for j in range(2*i, x+1, i):
                a[j] = False
    return primes
            
def num_primorial(n):
    result = 1
    primes = arr_primenumber(n**2)
    for i in primes[:n]:
        result *= i
    return result

 

 

 

Best Practice:

def num_primorial(n):
    primorial, x, n = 2, 3, n-1
    while n:
        if all(x % d for d in range(3, int(x ** .5) + 1, 2)):
            primorial *= x
            n -= 1
        x += 2
    return primorial

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

자료구조 _ Queue 그리고 Stack  (0) 2022.03.20
Multiplication table  (0) 2022.03.19
자료구조 _ Linked List란?  (0) 2022.03.17
자료구조 _ Array와 Dynamic Array  (0) 2022.03.17
Meeting  (0) 2022.03.17