Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Jannik Spiessens
Jannik Spiessens
13,229 Points

Highest Prime Factor challenge

I am challenging myself to make a function in swift that receives an integer and returns the highest prime factor of that integer. I currently have something like that and it works but whenever I try it whit higher numbers, e.g. 100,000,000, it takes to long and my computer crashes. I was wondering if someone could give me some tips to speed up the function.

func getLargestPrimeFast(n: Int) -> Int? {
    var p = 1
    var pDiv = 0
    do {
        if n % p == 0 {
            pDiv = n / p
            for var i = 2;i <= pDiv - 1;i++ {
                if pDiv % i == 0 {
                    break
                }
                if i == pDiv - 1 {
                    return pDiv
                }
            }
            p++
        } else {
            p++
        }
    } while p < n
    return nil
}

1 Answer

Jannik Spiessens
Jannik Spiessens
13,229 Points

Does this make the function faster or just more suitable for the task?