1

I wrote down simple algorithm for checking if Mersenne number is prime:

def is_prime_mers(result, step, modulo):
    if result != 0:
        if step == 0:
            return False
        result = result ** 2 - 2
        if result >= modulo:
            result %= modulo
        return is_prime_mers(result, step - 1, modulo)
    return True

Generally I don't need to give result parameter when script calls this function however I need it for recursive calls.

So only result need to be initialised for this function with value of 4

I can write some initializing function like:

def is_prime_mers_init(step):
    is_prime_mers(4, step, count_mersenne(step))

But maybe there is some python/general programming pattern to do that in first function?

Edit: For all curious ones :) This is function what implements Lucas-Lehmer test and checks if given Mersenne number is prime http://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test - however I read only mathematic implementation - so this is purely my code solution.

step is number of recursive calls

count_mersenne(step) gives value of some Mersenne number: 2 ** step - 1 however I use some check in count_mersenne(step) because searching for prime Mersenne numbers can be limited to prime step values.

3
  • 1
    What is count_mersenne and 4? Commented Apr 27, 2014 at 7:25
  • What would be the initial value of step and result be? Commented Apr 27, 2014 at 7:26
  • Initial value for result should be 4, step can be any, and basically count_mersenne value depends on step and returns Mersenne number so this value is set outside, for performance reason I excluded this computation from base function. Updated question. :) Commented Apr 27, 2014 at 7:58

1 Answer 1

2

You can assign them dummy default values and then you can decide whether to change them or not, like this

def is_prime_mers(step, result = None, modulo = None):
    if result is None:
        result = 4                    # Default value
    if modulo is None:
        modulo = count_mersenne(step)  # Default value

Or in one liners

def is_prime_mers(step, result = None, modulo = None):
    result = 4 if result is None else result
    modulo = count_mersenne(step) if modulo is None else modulo
Sign up to request clarification or add additional context in comments.

3 Comments

So how properly call this function is_prime_mers(?,7,127)?
@abrasadera That was what I was asking you, in my second comment in the question I guess. Could you please check that? :)
Grate thanx - If you can, just put to your answer example of this function called without self-initializing parameters - I'm new to Python so this is not explicit how it works:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.