Engee documentation
Notebook

The algorithm for calculating "Colored numbers"

This example demonstrates the implementation of the algorithm for searching for "colored numbers" in the Julia programming language.

Introduction

What are colored numbers?

A colored number is a natural number in which all the digits are different, and all possible products of consecutive digits are also different. For example, the number it is colored because:

  • numbers and different;
  • the product of all the digits () differs from the numbers themselves;
  • there are no more works.
    If we take the number Then we should check the following works:
  • one digit at a time: , , ;
  • two digits each: , ;
  • three digits each: .
    All these values are unique → the number is "colored".

Function iscolorful

Checks whether a given number is "colored"

Arguments:

  • n: an integer to check
  • base: number system (default is 10)

Returns: true/false

In [ ]:
function iscolorful(n, base=10)
    # Если число меньше 10, оно автоматически считается цветным
    0 <= n < 10 && return true
    
    # Получаем массив из цифр числа
    dig = digits(n, base=base)

    # Исключаем случаи: присутствие 1 или 0,
    # либо повторяющиеся цифры – такие числа точно не цветные
    (1 in dig || 0 in dig || !allunique(dig)) && return false

    # Создаём множество уникальных значений, начинаем с отдельных цифр
    products = Set(dig)

    # Проходим по всем подстрокам длиной >= 2
    # i – длина подстроки (от 2 до длины числа)
    # j – начальная позиция подстроки
    for i in 2:length(dig), j in 1:length(dig)-i+1
        # Вычисляем произведение цифер в текущей группе
        p = prod(dig[j:j+i-1])

        # Если такое значение уже встречалось, число не цветное
        p in products && return false
        
        # Добавляем новое произведение в множество
        push!(products, p)
    end

    # Обновляем глобальную переменную максимального найденного цветного числа
    if n > largest
        global largest = n
    end

    return true
end
Out[0]:
iscolorful
In [ ]:
# Глобальная переменная для хранения наибольшего цветного числа
largest = 0;

Testing functionality (testcolorfuls)

This function outputs a list of colored numbers from 1 to 100, and then counts the number of colored numbers in each decimal interval.

In [ ]:
function testcolorfuls()
    println("Цветные числа для диапазонов 1:25, 26:50, 51:75, и 76:100:")

    # Цикл по числам от 1 до 100
    for i in 1:100
        # Если число цветное — выводим его с форматированием
        iscolorful(i) && print(rpad(i, 5))

        # Разрыв строки каждые 25 чисел
        i % 25 == 0 && println()
    end

    csum = 0 # Общий счётчик цветных чисел

    # Подсчитываем цветные числа в диапазонах:
    # [0..9], [10..99], ..., [10^7...10^8)
    for i in 0:7
        # Начальный и конечный элементы интервала
        j, k = i == 0 ? 0 : 10^i, 10^(i+1) - 1

        # Считаем количество цветных чисел в интервале
        n = count(ii -> iscolorful(ii), j:k)

        csum += n

        # Печатаем результат
        println("Количество цветных чисел между $(lpad(j,9)) и $(lpad(k,9)) - $n.")
    end

    # Итоговой сообщение
    println("Максимально возможное цветное число - $largest.")
    println("Общее количество цветных чисел - $csum.")
end
Out[0]:
testcolorfuls (generic function with 1 method)

Calling the test function

Let's run the main code to get the result.

In [ ]:
testcolorfuls()
Цветные числа для диапазонов 1:25, 26:50, 51:75, и 76:100:
1    2    3    4    5    6    7    8    9    23   24   25   
26   27   28   29   32   34   35   36   37   38   39   42   43   45   46   47   48   49   
52   53   54   56   57   58   59   62   63   64   65   67   68   69   72   73   74   75   
76   78   79   82   83   84   85   86   87   89   92   93   94   95   96   97   98   
Количество цветных чисел между         0 и         9 - 10.
Количество цветных чисел между        10 и        99 - 56.
Количество цветных чисел между       100 и       999 - 328.
Количество цветных чисел между      1000 и      9999 - 1540.
Количество цветных чисел между     10000 и     99999 - 5514.
Количество цветных чисел между    100000 и    999999 - 13956.
Количество цветных чисел между   1000000 и   9999999 - 21596.
Количество цветных чисел между  10000000 и  99999999 - 14256.
Максимально возможное цветное число - 98746253.
Общее количество цветных чисел - 57256.

Conclusion

We have reviewed the implementation of the concept of a "colored number" in the Julia language. The program allows you to find such numbers, determine their uniqueness within the specified boundaries, as well as calculate their total number and maximum among them.
This is useful in studying the properties of numbers and can be applied in number theory problems or logic puzzles.
It uses working with sets, recursive analysis of subarrays, and management of global variables.

The example was developed using materials from Rosetta Code