Ad
Mathematics
Algorithms
Logic
Numbers
Data Types

Find Happy numbers

A number h is happy when iteratively summing the squares of its digits eventually leads 1.
For example 7 is happy because

7^2 = 49 -> 4^2 + 9^2 = 97 -> 9^2 + 7^2 = 130 -> 1^2 + 3^2 + 0^2 = 10 -> 1^2 + 0^2 = 1.

Similarly, 3 is unhappy, because 3^2 = 9.

Task

Write a function is_happy returning True if its integer input h is happy.

def is_happy(h: int) -> bool:
    """Returns `True` if `h` is happy, `False` otherwise."""
    seen = set()
    while h > 1 and h not in seen:
        seen.add(h)
        tot = 0
        while h > 0:
            tot += pow(h % 10, 2)
            h //= 10
        h = tot
    return h == 1
Mathematics
Algorithms
Logic
Numbers

Prime Checker [Optimized]

Write a function prime_checker taking a single integer input n and returning True if n is prime, False otherwise.

Code
Diff
  • """
    https://en.wikipedia.org/wiki/Primality_test
    This one has lesser tests or usage of % operator.
    An alternative using primality mod 30 = 2 * 3 * 5 instead of 6 = 2 * 3 
    """
    def prime_checker(n):
        if n in [2, 3, 5]:
            return True
        elif n % 2 == 0 or n % 3 == 0 or n % 5 == 0:
            return False
        
        a = int(n ** 0.5 / 30)
        b = [7, 11, 13, 17, 19, 23, 29, 31]
        
        for i in [30 * j for j in range(a)]:
            if True in [n % (i + q) == 0 for q in b]:
                return False
        return True 
    • """
    • https://en.wikipedia.org/wiki/Primality_test
    • This one has lesser tests or usage of % operator.
    • An alternative using primality mod 30 = 2 * 3 * 5 instead of 6 = 2 * 3
    • """
    • def prime_checker(n):
    • if n in [2, 3, 5]:
    • return True
    • elif n % 2 == 0 or n % 3 == 0 or n % 5 == 0:
    • return False
    • a = int(n ** 0.5 / 30)
    • b = [7, 11, 13, 17, 19, 23, 29, 31]
    • for i in [30 * j for j in range(a)]:
    • if True in [n % (i + q) == 0 for q in b]:
    • return False
    • return True
    • return True