How to calculate all the less than 500 additive prime numbers in Swift

1 Answer

0 votes
// Additive primes: primes whose sum of digits is also prime

import Foundation

// Check if a number is prime
func isPrime(_ n: UInt) -> Bool {
    if n < 2 { return false }
    if n % 2 == 0 { return n == 2 }
    if n % 3 == 0 { return n == 3 }

    var i: UInt = 5
    while i * i <= n {
        if n % i == 0 { return false }
        i += 2
        if n % i == 0 { return false }
        i += 4
    }
    return true
}

// Compute the sum of digits of a number
func sumDigits(_ n: UInt) -> UInt {
    var x = n
    var sum: UInt = 0
    while x > 0 {
        sum += x % 10
        x /= 10
    }
    return sum
}

// Check if a number is an additive prime
func isAdditivePrime(_ n: UInt) -> Bool {
    return isPrime(n) && isPrime(sumDigits(n))
}

let TOP: UInt = 500
var count = 0
var line = ""

// Main loop
for n in 1..<TOP {
    if isAdditivePrime(n) {
        line += String(format: "%3d ", Int(n))
        count += 1

        if count % 10 == 0 {
            print(line.trimmingCharacters(in: .whitespaces))
            line = ""
        }
    }
}

if !line.isEmpty {
    print(line.trimmingCharacters(in: .whitespaces))
}

print()
print("Total additive primes = \(count)")



/*
run:

2   3   5   7  11  23  29  41  43  47
61  67  83  89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487

Total additive primes = 54

*/

 



answered May 4 by avibootz
...