Prime factorization is useful for reshaping an array into the highest dimension form where non of the dimension has size of 1.
Created
May 4, 2022 13:56
-
-
Save sklam/2c51085e04afb4500563b940fff22f80 to your computer and use it in GitHub Desktop.
prime factorization using trial division
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
import numpy as np | |
def prime_factorize(n: int): | |
# trial division | |
assert n > 0 | |
factors = [] | |
if n < 2: | |
return [1] | |
while n % 2 == 0: | |
factors.append(2) | |
n //= 2 | |
for x in range(2, int(math.ceil(math.sqrt(n)))): | |
while n % x == 0: | |
factors.append(x) | |
n //= x | |
if n != 1: | |
factors.append(n) | |
return factors | |
def test_prime_factorize(): | |
for x in range(1, 1000): | |
factors = prime_factorize(x) | |
assert np.prod(factors) == x | |
random.seed(44) | |
for _ in range(1000): | |
x = random.randint(1000, 1000000) | |
factors = prime_factorize(x) | |
assert np.prod(factors) == x | |
def test_prime_factorize_reshape(): | |
for x in range(1, 1000): | |
factors = prime_factorize(x) | |
arr = np.random.random(x) | |
# success in reshape is the test | |
arr.reshape(factors) | |
for _ in range(1000): | |
x = random.randint(1000, 1000000) | |
factors = prime_factorize(x) | |
arr = np.random.random(x) | |
# success in reshape is the test | |
arr.reshape(factors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment