这只是我一直在努力的项目。但我需要你的帮助。我想用我存储在数组中的数字做一些数学运算。但我不能正确编码。有人可以解释一下我做错了吗?
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])")
}
}
我想知道如何提取素数以结束素数。
帮助我们!
干杯!
答案 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]