[Python] Calculating large numbers in a RAM efficient way

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using the following code to calculate modulus for large numbers in a RAM efficient way. This is from another question's answer.

    def geom(a,k,n):
    """calculates (1 + a + a^2 + ... + a^(k-1)) mod n)"""
    if k <= 2:
    return sum(a**i for i in range(k)) % n
    else:
    m = k//2
    b = pow(a,2,n)
    g = ((1+a)*geom(b,m,n))%n
    return g if k%2 == 0 else (g + pow(a,k-1,n))%n

    def f(a,m,n):
    """ returns aaaa...a (m times) modulo n"""
    k = len(str(a))
    r = pow(10,k,n)
    return (a*geom(r,m,n))%n


    For example,

    >>> f(366, 457429086499,164868357)
    2013258


    I am a novice python user and would like help to modify the above code to calculate:

    1. a**m or a (m times) alone
    2. log(a) / log(b)
    3. a / b**(x-1)

    Continue reading...

Compartilhe esta Página