Swift,如何使用数组中存储的数字进行数学运算

时间:2016-08-12 14:17:17

标签: ios arrays swift math

这只是我一直在努力的项目。但我需要你的帮助。我想用我存储在数组中的数字做一些数学运算。但我不能正确编码。有人可以解释一下我做错了吗?

var primeNumbers = [Int]()

// Here I search for the prime numbers till a 100
let numbers = 2...100

for n in numbers {
       //set the flag to true initially
    var prime = true


    for var i = 2; i <= n - 1; i += 1 {

        //even division of a number thats not 1 or the number itself, not a prime number
        if n % i == 0 {
            prime = false
            break
        }
    }
    if prime == false {
}
    else {
        primeNumbers += [n]
        prime = true
    }
}

primeNumbers

//Here I want to see how to extract the prime number, with the prime //numbers stored in the array.
func ontbinden(i: Int){
    var antwoord = i % primeNumbers[0...24]
    if antwoord == 0{
        print("\(i)","is extracted by \(primeNumbers[0...24])")
    }


}

我想知道如何提取素数以结束素数。

帮助我们!

干杯!

1 个答案:

答案 0 :(得分:0)

这条线没有意义。您无法将%应用于Int[Int]的数组切片:

var antwoord = i % primeNumbers[0...24]

您需要一次选择一个素数。像这样的东西会起作用:

func ontbinden(i: Int) {
    for prime in primeNumbers {
        if i % prime == 0 {
            print("\(i)","is divisible by \(prime)")
        }
    }
}

您可以使用filter创建一个用于划分数字的素数数组:

func ontbinden(i: Int) {
    let result = primeNumbers.filter { prime in i % prime == 0 }
    print("\(i) is divisible by \(result)")
}

ontbinden(56)  // 56 is divisible by [2, 7]
ontbinden(30)  // 30 is divisible by [2, 3, 5]
ontbinden(42)  // 42 is divisible by [2, 3, 7]