Additive Prime Algorithm
Introduction
Additive prime is a prime number whose digits add up to another prime number. For example, 23 is an additive prime because 2 + 3 = 5, and both 23 and 5 are prime numbers. This algorithm checks whether a given number is an additive prime.
Implementation
The algorithm is implemented in OCaml. The function digit_sum calculates the sum of digits of a given number. The function is_prime checks whether a given number is prime. The function is_additive_prime checks whether a given number is an additive prime by checking if the number and its digit sum are both prime.
let rec digit_sum n =
if n < 10 then n else n mod 10 + digit_sum (n / 10)
let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let is_additive_prime n =
is_prime n && is_prime (digit_sum n)
Here is an example.
let () =
Seq.ints 0 |> Seq.take_while ((>) 500) |> Seq.filter is_additive_prime
|> Seq.iter (Printf.printf " %u") |> print_newline
Step-by-step Explanation
- The function
digit_sumtakes a positive integernas input. - If
nis less than 10, thennis returned as the sum of digits of a single-digit number is the number itself. - If
nis greater than or equal to 10, then the last digit ofnis added to the sum of digits of the remaining digits ofnby recursively calling thedigit_sumfunction. - The function
is_primetakes a positive integernas input. - If
nis less than 5, thennis prime if and only if it is equal to 2 or 3. - If
nis greater than or equal to 5, then the functiontestis called with an initial value of 5. - The function
testtakes a positive integerxas input and checks ifnis divisible byxorx + 2, or ifnis divisible by any number of the formx + 6kwherekis a non-negative integer less than or equal to(n / x - x) / 6. - If
xis greater than(n / x - x) / 6, thennis prime. - The function
is_additive_primetakes a positive integernas input. - If
nis not prime, thenis_additive_primereturnsfalse. - If
nis prime, then the functiondigit_sumis called withnas input. - If the digit sum of
nis not prime, thenis_additive_primereturnsfalse. - If both
nand its digit sum are prime, thenis_additive_primereturnstrue.
Complexity Analysis
The time complexity of the digit_sum function is O(log n) as the number of digits in n is proportional to log n. The time complexity of the is_prime function is O(sqrt n) as it checks divisibility up to the square root of n. The worst-case time complexity of the is_additive_prime function is O(sqrt n log n) as it checks the primality of n and its digit sum, which each have a worst-case time complexity of O(sqrt n). The space complexity of all