📌  相关文章
📜  将给定的二进制数从L转换为R后的素数计数

📅  最后修改于: 2021-05-05 01:18:04             🧑  作者: Mango

给定一个二进制数N ,并用LR表示一个范围,任务是将给定的二进制数转换为L和R之间的所有基数(包括L和R),并计算其中的素数。

例子:

方法:将给定的二进制数一个接一个地转换为’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