find the average of the log of primes in swift

Here's some code in Swift that calculates the average of the logarithm of the first 100 primes:

main.swift
import Foundation

func isPrime(_ n: Int) -> Bool {
    if n < 2 { return false }
    for i in 2..<n {
        if n % i == 0 {
            return false
        }
    }
    return true
}

func primes(n: Int) -> [Int] {
    var result = [Int]()
    var i = 2
    while result.count < n {
        if isPrime(i) {
            result.append(i)
        }
        i += 1
    }
    return result
}

let primeNumbers = primes(n: 100)
let logPrimes = primeNumbers.map { log(Double($0)) }
let averageLog = logPrimes.reduce(0, +) / Double(logPrimes.count)
print("Average of log(primes) =", averageLog)
590 chars
29 lines

The isPrime function tests whether a number is prime using a brute force method, checking all numbers from 2 up to n-1. The primes function generates a list of the first n prime numbers.

We then map the log() function over each of the prime numbers to get their natural logarithm. Finally, we use the reduce function to sum up the log values and divide by the total number of primes to get the average value of the logged primes.

gistlibby LogSnag