Skip to content

Instantly share code, notes, and snippets.

@iuriguilherme
Created February 2, 2026 00:55
Show Gist options
  • Select an option

  • Save iuriguilherme/b0a376688db921d60ac3d792a6b7d74b to your computer and use it in GitHub Desktop.

Select an option

Save iuriguilherme/b0a376688db921d60ac3d792a6b7d74b to your computer and use it in GitHub Desktop.
How long does this machine allows you to stare at the terminal until you find out there's no power of 2 divisible by 7
"""
Finds the lowest power of initial_exponent that is divisible by initial_modulo.
Uses mpmath library for arbitrary-precision arithmetic.
Uses colorama to do nothing useful.
pip install colorama mpmath
"""
## Configuration
# Change to start from a different iteration if restarting
initial_power: int = 2
initial_exponent: int = 2
initial_modulo: int = 2
# Whether to increment modulo/power and continue searching after finding a result
# need to set increase_modulo to True if continue_next is True, otherwise it makes no sense
continue_next: bool = True
# Whether to limit search on thresholds
give_up_power: bool = True
give_up_power_at: int = int(1e3)
# Only works if give_up_power is True
increase_modulo: bool = True
give_up_modulo: bool = True
give_up_modulo_at: int = int(1e3)
# Only works if give_up_modulo is True
increase_power: bool = True
give_up_power: bool = True
give_up_power_at: int = int(1e2)
## End configuration
name: str = 'p2nm7e0'
import logging
# logging.basicConfig(level = 'WARNING')
logging.basicConfig(level = 'INFO')
# logging.basicConfig(level = 'DEBUG')
logger: logging.Logger = logging.getLogger(name)
import functools
import inspect
import os
import sys
from typing import Union
try:
import colorama
from mpmath import mp, power as p
except ImportError as e:
logger.exception(e)
sys.exit("pip install colorama mpmath")
mp.dps = 50
min_power: int = 2
min_modulo: int = 2
min_exponent: int = 2
result: mp.mpf = mp.mpf(0)
power: int = initial_power
target_modulo: int = initial_modulo
exponent: int = initial_exponent
modulo: int = 0
is_divisible: bool = False
last_result: mp.mpf = result
last_power: int = power
over: bool = False
found: dict[int, dict[int, int]] = {}
colorama.init()
default_color: tuple[object] = (colorama.Fore.WHITE, colorama.Back.BLACK)
default_color_map: dict[str, tuple[object]] = {
'0': (colorama.Fore.BLACK, colorama.Back.WHITE),
'1': (colorama.Fore.RED, colorama.Back.BLACK),
'2': (colorama.Fore.GREEN, colorama.Back.BLACK),
'3': (colorama.Fore.YELLOW, colorama.Back.BLACK),
'4': (colorama.Fore.BLUE, colorama.Back.BLACK),
'5': (colorama.Fore.MAGENTA, colorama.Back.BLACK),
'6': (colorama.Fore.CYAN, colorama.Back.BLACK),
'7': (colorama.Fore.WHITE, colorama.Back.BLACK)
}
# Create a dictionary comprehension for different values of to_modulo if needed
# Maps 0 -> color 0 (always), and distributes remaining values proportionally across remaining colors
def set_color_map(to_modulo: int) -> dict[str, tuple[object]]:
return {
str(i): list(default_color_map.values())[
0 if i == 0 or to_modulo == 1 else 1 + ((i - 1) * (len(default_color_map) - 1)) // (to_modulo - 1)
] for i in range(to_modulo)
}
color_map: dict[str, tuple[object]] = set_color_map(target_modulo)
def colorize_string(string: Union[float, int, str], *args, **kwargs) -> str:
"""Returns a color version of a string defined in a map"""
logger: logging.getLogger = logging.getLogger(inspect.currentframe().f_code.co_name)
try:
return ''.join([''.join([
colorama.Style.BRIGHT,
color_map.get(n, default_color)[0],
color_map.get(n, default_color)[1],
n,
colorama.Style.RESET_ALL,
]) for n in str(string)])
except Exception as e:
logger.exception(e)
def colorize_for(string: Union[float, int, str], number: int, *args, **kwargs) -> str:
"""Returns a color version of a string defined in a map from a number"""
logger: logging.getLogger = logging.getLogger(inspect.currentframe().f_code.co_name)
try:
return ''.join([''.join([
colorama.Style.BRIGHT,
color_map.get(str(number), default_color)[0],
color_map.get(str(number), default_color)[1],
n,
colorama.Style.RESET_ALL,
]) for n in str(string)])
except Exception as e:
logger.exception(e)
def progress(*args, **kwargs) -> None:
"""Logs the current status"""
logger: logging.getLogger = logging.getLogger(inspect.currentframe().f_code.co_name)
global last_result
global last_power
try:
logger.info(colorize_for(f"Checking if pow({exponent}, {power}) is divisible by {target_modulo}: {str(result)} % {target_modulo} = {modulo}, result: {is_divisible}", modulo))
last_result = result
except ValueError:
try:
logger.info(colorize_for(f"Checking if pow({exponent}, {last_power}) is divisible by {target_modulo}: {str(last_result)} % {target_modulo} = {modulo}, result: {is_divisible}", modulo))
last_power = power
except ValueError:
logger.info(colorize_for(f"Checking if pow({exponent}, {last_power}) is divisible by {target_modulo}: {str(last_result)} % {target_modulo} = {modulo}, result: {is_divisible}", modulo))
def restart(*args, **kwargs) -> None:
"""Continue to next modulo/power as per configuration"""
logger: logging.getLogger = logging.getLogger(inspect.currentframe().f_code.co_name)
global color_map
global power
global target_modulo
global exponent
global over
power = min_power
if increase_modulo:
logger.warning(f"Increasing modulo from {target_modulo} to {target_modulo + 1}.")
target_modulo += 1
color_map = set_color_map(target_modulo)
if give_up_modulo and (target_modulo >= give_up_modulo_at):
logger.warning(f"Giving up on modulo increase at modulo {target_modulo}.")
if increase_power:
logger.warning(f"Increasing power from {exponent} to {exponent + 1}.")
target_modulo = min_modulo
color_map = set_color_map(target_modulo)
exponent += 1
if give_up_power and (exponent >= give_up_power_at):
logger.warning(f"Giving up on power increase at power {exponent}.")
over = True
return
else:
over = True
return
#@functools.lru_cache(maxsize=None)
def main(*args, **kwargs) -> None:
"""Main function"""
logger: logging.getLogger = logging.getLogger(inspect.currentframe().f_code.co_name)
global color_map
global power
global target_modulo
global exponent
global over
global is_divisible
global result
global modulo
try:
if exponent < min_exponent:
logger.warning(f"Exponent {exponent} is less than minimum {min_exponent}, resetting exponent to minimum.")
exponent = min_exponent
if power < min_power:
logger.warning(f"Power {power} is less than minimum {min_power}, resetting power to minimum.")
power = min_power
if target_modulo < min_modulo:
logger.warning(f"Modulo {target_modulo} is less than minimum {min_modulo}, resetting modulo to minimum.")
target_modulo = min_modulo
if target_modulo >= exponent:
logger.warning(f"Modulo {target_modulo} is greater or equal to power {exponent}, resetting modulo to minimum {min_modulo}.")
target_modulo = min_modulo
if increase_power:
logger.warning(f"Increasing power from {exponent} to {exponent + 1}.")
exponent += 1
if give_up_power and (exponent >= give_up_power_at):
logger.warning(f"Giving up on power increase at power {exponent}.")
over = True
return
result = p(exponent, power)
try:
modulo = int(result) % target_modulo
except ZeroDivisionError:
logger.warning(f"Zero division error for {result} modulo {target_modulo}, incrementing target_modulo.")
target_modulo += 1
color_map = set_color_map(target_modulo)
return
is_divisible = (modulo == 0)
progress()
if is_divisible:
logger.warning(f"Divisible found! pow({exponent}, {power}) % {target_modulo} = 0")
if exponent not in found:
found[exponent] = {}
found[exponent][target_modulo] = power
if continue_next:
logger.warning("Continuing to next modulo/power as per configuration.")
is_divisible = False
restart()
return
power += 1
if give_up_power and (power >= give_up_power_at):
logger.warning(f"Giving up at iteration {power}.")
restart()
# except KeyboardInterrupt:
# logger.warning(f"Last check was if pow({to_power}, {last_iteration}) was divisible by {to_modulo}: {str(last_power)} % {to_modulo} = {modulo}, result: {is_divisible}")
# over = True
# return
except Exception:
raise
if __name__ == '__main__':
logger.info(f"Checking colors for alphabet of {target_modulo} size:")
for z in range(0, target_modulo):
logger.info(colorize_for(f"Color for {z}", z))
logger.warning(f"Looking for the smallest power of {exponent} divisible by {target_modulo}...")
try:
while ((not give_up_power) or (power < give_up_power_at)) and (not is_divisible) and (not over):
try:
main()
# except KeyboardInterrupt:
# logger.warning(f"Last check was if pow({to_power}, {last_iteration}) was divisible by {to_modulo}: {str(last_power)} % {to_modulo} = {modulo}, result: {is_divisible}")
# over = True
except Exception as e:
logger.exception(e)
break
except KeyboardInterrupt:
logger.warning(f"Last check was if pow({exponent}, {last_power}) was divisible by {target_modulo}: {str(last_result)} % {target_modulo} = {modulo}, result: {is_divisible}")
print("\n" + "="*os.get_terminal_size().columns + "\n")
if continue_next:
if found:
for k,v in found.items():
for k2, v2 in v.items():
logger.warning(f"Lowest power of {k} divisible by {k2}: pow({k}, {v2}).")
else:
logger.warning("No results found.")
else:
logger.warning(f"\nLowest power of {exponent} divisible by {target_modulo}:", end=" ")
if is_divisible:
try:
logger.warning(f"pow({exponent}, {power}).", end=" ")
except ValueError:
logger.warning(f"Too big for print. Last which could be displayed: pow({exponent}, {last_power}).", end=" ")
try:
logger.warning(f"Which is: {str(result)}.")
except ValueError:
logger.warning(f"Which is too big for print. Last which could be displayed: {str(last_result)}.")
else:
logger.warning(f"None. Last checked: pow({exponent}, {power})")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment