Created
July 28, 2017 16:27
-
-
Save Juice805/500ee740b373614bab17aec993ee370e to your computer and use it in GitHub Desktop.
Swift Navigation Application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Written.... In Swift | |
import Foundation | |
/// Generates the first n Fibonacci numbers printing | |
/// "Buzz" when F(n) is divisible by 3. | |
/// "Fizz" when F(n) is divisible by 5. | |
/// "FizzBuzz" when F(n) is divisible by 15. | |
/// "BuzzFizz" when F(n) is prime. | |
/// the value F(n) otherwise. | |
/// | |
/// - Parameter n: number of Fibonacci numbers to print | |
func FizzBuzz(n: Int) { | |
// If n < 2 only print "seed" values | |
let x = (n >= 1) ? 1 : 0; | |
// print up to and including x (Maximum 1) | |
for num in 0...x { | |
print(num) | |
} | |
// Continue Sequence only for numbers above 1 | |
guard (n > 1) else { | |
return | |
} | |
// Storage for previous numbers in sequence | |
var prevValues = [ 0 , 1] | |
for num in 2...n { | |
var newValue = prevValues[0] + prevValues[1] | |
var specialCase = false | |
if (isPrime(num: newValue)) { | |
print("BuzzFizz", terminator: "") | |
specialCase = true | |
} else { | |
// Divisible by 5 | |
if (newValue % 5 == 0) { | |
print("Fizz", terminator: "") | |
specialCase = true | |
} | |
// Divisible by 3 | |
if (newValue % 3 == 0) { | |
print("Buzz", terminator: "") | |
specialCase = true | |
} | |
// Print number | |
if (!specialCase) { | |
print(newValue, terminator: "") | |
} | |
} | |
// Add new line | |
print("") | |
prevValues[0] = prevValues[1] | |
prevValues[1] = newValue | |
} | |
} | |
/// Checks if input is a prime number | |
/// | |
/// - Returns: true for prime number input | |
func isPrime(num: Int) -> Bool { | |
guard num > 1 else { | |
return false | |
} | |
var i = 2 | |
// Only need to check up to square root of input | |
// C style for loops deprecated in Swift, must use while | |
while (i*i <= num) { | |
// Not a prime if has factor | |
if (num % i == 0) { | |
return false | |
} | |
i += 1 | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment