简体   繁体   中英

Mersenne number formula in Python

A Mersenne number is any number that can be written as 2^p−1 for some p. For example, 3 is a Mersenne number (2^2-1) as is 31 (2^5-1). Write a function that accepts an exponent p and returns the corresponding Mersenne number.

def mersenne number(p):
   return ((2**p)-1)

I'm just at the start of my programming course and I get stuck in simply things. I wrote that so far and have no idea how to make it to the end, and even if that is correct so far. I''l be grateful for any help from your side.

You cannot have spaces in your function names.

Usually in Python, we use underscores to separate words in functions:

def mersenne_number(p):
   return ((2**p)-1)

Link to: PEP 8 -- Style Guide for Python Code

That's fine, except for one thing: The name of the function must not contain spaces. So you might want to write def mersenne_number(p) instead. And you might want to validate that p is actually an integer:

def mersenne_number(p: int) -> int:
   if not isinstance(p, int):
       raise TypeError("p must be integer")

   return ((2**p)-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM