How to print all divisors of a number

[Question] Print all divisors of a given number For example divisors of 36 are = 1,2,3,4,5,9,12,18,36
#Approach: We can find square root of a given number & check if its perfectly divisible sqrt numbers

// TC: O(√n)
// SC: O(1)
func printAllDivisors(_ n: Int) {
    for i in 1...Int(sqrt(Double(n))) {
        if n%i == 0 {// Filter non divisibles.
            print("divisior",i, separator: " ")
            if i != n/i {
                print("divisior--",n/i, separator: " ")
            }
        }
    }
}
let n = 36
printAllDivisors(n) // 1 36 2 18 3 12 4 9 6

Leave a Comment

Your email address will not be published. Required fields are marked *