English 中文(简体)
最小N, nn mod m = 0
原标题:The smallest n such that n^n mod m = 0

你们自然有一米。

您需要写一份功能(m),该功能的正数最小,即零度。

换言之,N^n可以分为m。

例如:

f(13) = 13
f(420) = 210
f(666) = 222
f(1234567890) = 411522630

And this is my code for python.

import math

def f(m: int) -> int:
    t = math.isqrt(m) + 1
    primes = [1 for i in range(0, t)]

    maxCount = 0
    factors = []
    p = 2

    result = 1

    while p < t and p < m:
        if primes[p] == 1 and m % p == 0:
            for i in range(p + p, t):
                primes[i] = 0

            c = 0
            while m % p == 0:
                m = m // p
                c += 1
            if maxCount < c:
                maxCount = c
            result *= p
            factors.append(p)
        p += 1
    factors.append(p)
    if m > 1:
        result *= m
    if maxCount <= result:
        return result
    p1 = math.ceil(maxCount / result)
    for p in primes:
        if p >= p1:
            return result * p
    return result

The problem is, the result is usually gets bigger than it has to be. If you have ever met this question before, please help me how can I solve this problem.

I have tried to find the mathematical methods, and this code is what I have reached so far. I hope this code will get me the smallest result, but it gets bigger than I expected.

问题回答

If m divides nn, Then all the prime factors of m must also be factors of nn.

Since exponentiation doesn t introduce any new prime factors, n itself must also have all the prime factors of m.

Let P be the product of the unique prime factors of m. Since n needs all of these factors, it will be a multiple of P.

n = P将发挥作用,即PP将可分到m, Unless 至少是m的主要动力,大于P。

For example, if m = 3x27, then P = 6, and 66 is not divisible by 3x27, because it only has 26.

However, if you just start with i=1 and just try each n = Pi in sequence, then you will never have to count very far before you find a multiple of m, because the powers of the prime factors in m are limited by the length of m.

To solve this problem, we will follow the given steps:

1. 开始与否

Check if n ^n mod m = 0. If true, return n.

如果是假的,那么加固就等于或重复第二步。

Below is the Python code that implements the function:

def f(m):
    n = 1
    while True:
        if pow(n, n, m) == 0:
            return n
        n += 1

# Test the function with given examples
print(f(13))  # 13
print(f(420))  # 210
print(f(666))  # 222
print(f(1234567890))  # 411522630

This function uses the built-in pow function with three arguments: pow(a, b, m) computes a^b mod m efficiently. This allows the program to compute large powers modulo m without having to compute the large power directly.

Note: For very large values of m, this algorithm might take a considerable amount of time because it checks each possible value of n iteratively.

The solution is to factorise m such that you know the prime factors as well as their multiplicity in m, i.e. a prime power factorisation. All primes in this factorisation must appear at least once in our initial pass over n, and then we can just multiply it by the roof of the largest power divided by the result of the unitary power of each prime.

可执行;

import math

def extract_factor(m, f):
    p = 0
    while m%f == 0:
        p += 1
        m //= f
    return (m, p)

def prime_power_factorise(m):
    factors = {}
    if m%2 == 0:
        m, factors[2] = extract_factor(m, 2)
    if m%3 == 0:
        m, factors[3] = extract_factor(m, 3)
    sliding_window = 1
    while m > 1:
        for multiple_of_six in range(6*sliding_window, m+1, 6):
            reduced = False
            for factor in [multiple_of_six-1, multiple_of_six+1]:
                if m%factor == 0:
                    m, factors[factor] = extract_factor(m, factor)
                    reduced = True
            if reduced:
                sliding_window = multiple_of_six // 6 + 1
                continue
    return factors

def modular_zero_root(m):
    result = 1
    for prime, power in prime_power_factorise(m).items():
        result *= prime**math.ceil(power/2)
    return result

# Find the modular "super root" of a tetration
def modular_zero_superroot(m):
    result = 1
    prime_factors = prime_power_factorise(m)
    largest_power = max(prime_factors.values())
    # Firstly, the result must have every prime factor
    for prime in prime_factors.keys():
        result *= prime
        prime_factors[prime] -= 1
    # But now we must ensure the result is greater than
    # or equal to to the largest power of a prime in m.
    result *= math.ceil(largest_power/result)
    return result

回答所提供例子所需的时间;

import time

start = time.time()
val = modular_zero_superroot(1234567890)
end = time.time()
print(f {val} in {end - start} )

# 411522630 in 1.8367185592651367




相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签