给定一个二进制数N ,并用L和R表示一个范围,任务是将给定的二进制数转换为L和R之间的所有基数(包括L和R),并计算其中的素数。
例子:
Input: N = 111, L = 3, R = 10
Outpu: 5
Explanation:
When 111 is interpreted in all the base numbers between 3 and 10 we get the resulting numbers as [21, 13, 12, 11, 10, 7, 7, 7], out of which only 5 numbers are prime. Hence, the output is 5.
Input: N = 11, L = 4, R = 19
Output: 16
Explanation:
When 11 is interpreted in all the base numbers between 4 and 19 we get the resulting numbers as 3 which is a prime number. Hence, the output is 16.
方法:将给定的二进制数一个接一个地转换为’L’和‘R’之间的每个基数。此后,检查结果数是否为质数。如果是,则增加计数。
下面是上述方法的实现:
# Python3 program to count of primes
# after converting given binary
# number in base between L to R
# Function to interpret the binary number in all
# the base numbers between L and R one by one
def calc(binary, interpret_language):
# Temporary integer as intermediate
# value in a known language
tmp = 0
# Represenation of digits in base 2
base = "01"
# For each digit in the 'binary'
# get its index and its value
for n, digit in enumerate(binary[::-1]):
tmp += base.index(digit)*len(base)**n
# Generate the 'resulting_number' by appending
resulting_number = ''
while tmp:
resulting_number += interpret_language[tmp % len(interpret_language)]
# reduce the value of tmp
tmp //= len(interpret_language)
return resulting_number
# Function to check if the resulting
# number is prime or not
def IS_prime (N):
n = int(N)
c = 1
for i in range (2, n + 1):
if (n % i == 0):
c+= 1
if (c == 2):
return 1
return 0
# Driver program
if __name__ == '__main__':
binary = "111"
L = 3
R = 10
bases = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
b = bases[0:R]
# Count all the resulting numbers which are prime
count = 0
for i in range (R-L + 1):
# 'list' indicates representation of digits
# in each base number
list = b[:(L + i)]
# Converting in string
interpret_language = ''.join(map(str, list))
# Converting the binary number to the respective
# base between L and R
resulting_number = calc(binary, interpret_language)
if(IS_prime(resulting_number) == 1):
count+= 1
print (count)
输出:
5