Attractive Numbers
This example shows the implementation of an algorithm for finding attractive numbers from 1 to 120.
Introduction
The algorithm of "attractive numbers" is a curious mathematical problem that involves determining natural numbers whose sum of prime factors is a prime number.
What is factorization?
Each natural number can be represented as a product of prime numbers (factors). For example:
- The number 12 has prime factors , or a record based on degrees — .
Function factor in Julia, it decomposes the input number exactly like this.
What does the number “attractive" mean?
A number is considered attractive when the sum of allits unique prime factors (without taking into account the degree) is a prime number.
Let's explain:
- For the number 12: factorization → [2, 3] ? sum = 2 + 3 = 5.
- Since 5 is a prime number, 12 is an attractive number.
We need to find all such numbers in the range from 1 to 120.
Problem solving
Installing the required package
import Pkg; Pkg.add("Primes")
Connecting the module Primes. It provides functions for working with prime numbers, for example, isprime() checks if a number is prime
using Primes
Function isattractive(n) accepts a positive integer n, then:
- 
factor(n)— we get a dictionary of prime divisors with degrees
- 
values(...)— we take only values (ignore degrees)
- 
sum(...)— adding up the values
- 
isprime(...)— are we checking if this amount is simple?
function isattractive(n)
    return isprime(sum(values(factor(n))))
end
Function printattractive(m, n):
- 
accepts two arguments - the boundaries of the range from mbeforen
- 
causes filtering of the m:n array using the function isattractive()
- 
outputs a beautifully formatted list of numbers via println()
function printattractive(m, n)
    println("Привлекательные числа от $m до $n:\n", filter(isattractive, m:n))
end
Running calculations, the function created above with the specified range is called.
printattractive(1, 120)
Conclusion
Using this example, we have learned how to solve an interesting mathematical problem about "attractive" numbers using the features of the Julia programming language. We:
- Have you learned how to use the library Primesfor working with prime numbers;
- Used the built-in function factor()fromBase.Math(part of the standard library);
- We have written a function that checks whether a number is attractive;
- Implemented a convenient way to display the result in the terminal.
This approach demonstrates the elegance and readability of Julia code, especially when combining powerful built-in tools and concise syntax.
The example was developed using materials from Rosetta Code