Check whether a number can be written as a^b + b^a (Leyland number)

Quick Overview

Decide whether a positive integer up to 10^18 is a Leyland number, meaning it can be written as a^b + b^a with a and b both greater than 1. It tests bounding a brute-force search by exponential growth and computing large powers without overflow or floating-point error.

Check whether a number can be written as a^b + b^a (Leyland number)

Company: Toyota

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given a positive integer `n`, determine whether it is a Leyland number. A Leyland number is a positive integer that can be expressed as $a^b + b^a$, where $a$ and $b$ are integers with $a > 1$ and $b > 1$. Return `True` if such a pair `(a, b)` exists, and `False` otherwise. ### Function Signature ```python def is_leyland(n: int) -> bool: ``` ### Rules - `a` and `b` may be equal. - Both `a` and `b` must be at least 2. A pair that uses 1 does not count. ### Constraints - `1 <= n <= 10^18` ### Examples ```text Input: n = 8 Output: True ``` With $a = b = 2$, the sum is ${2^2 + 2^2 = 4 + 4 = 8}$. ```text Input: n = 10 Output: False ``` The only pair whose sum is at most 10 is $a = b = 2$, which gives 8. The next smallest sum is ${2^3 + 3^2 = 17}$, so no pair reaches exactly 10. ```text Input: n = 100 Output: True ``` With $a = 2$ and $b = 6$, the sum is ${2^6 + 6^2 = 64 + 36 = 100}$.

Overview: Decide whether a positive integer up to 10^18 is a Leyland number, meaning it can be written as a^b + b^a with a and b both greater than 1. It tests bounding a brute-force search by exponential growth and computing large powers without overflow or floating-point error.

Toyota logo
Toyota
Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer n, determine whether it is a Leyland number.

A Leyland number is a positive integer that can be expressed as ab+baa^b + b^a, where aa and bb are integers with a>1a > 1 and b>1b > 1.

Return True if such a pair (a, b) exists, and False otherwise.

Function Signature

def is_leyland(n: int) -> bool:

Rules

  • a and b may be equal.
  • Both a and b must be at least 2. A pair that uses 1 does not count.

Constraints

  • 1 <= n <= 10^18

Examples

Input: n = 8
Output: True

With a=b=2a = b = 2, the sum is 22+22=4+4=8{2^2 + 2^2 = 4 + 4 = 8}.

Input: n = 10
Output: False

The only pair whose sum is at most 10 is a=b=2a = b = 2, which gives 8. The next smallest sum is 23+32=17{2^3 + 3^2 = 17}, so no pair reaches exactly 10.

Input: n = 100
Output: True

With a=2a = 2 and b=6b = 6, the sum is 26+62=64+36=100{2^6 + 6^2 = 64 + 36 = 100}.