Skip to content

Instantly share code, notes, and snippets.

@InfiniteFalltrough
Created September 15, 2023 13:16
Show Gist options
  • Save InfiniteFalltrough/904b003fa9c29daf4854384b01de7e52 to your computer and use it in GitHub Desktop.
Save InfiniteFalltrough/904b003fa9c29daf4854384b01de7e52 to your computer and use it in GitHub Desktop.
answer[3]
#!/usr/bin/env xcrun --sdk macosx swift
/// Run: swift answer\[3\].swift
import Foundation
enum CustomError: Error {
case msg(String)
}
func calculateSeries(_ n: Int) throws -> Double {
var cur: Double = 0
if n < 2 {
throw CustomError.msg("Invalid input")
}
for i in 2...n {
cur += 1 / (Double(i) * Double(i - 1))
}
return cur
}
func test() {
let n = 2
do {
let result = try calculateSeries(n)
print(result)
} catch {
print(error.localizedDescription)
}
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment