Ad space (banner)
๐ŸฆSwift Lessons
Lesson 67 / 68

Prime Factorization

In this lesson you will learn how to factor a number into primes in Swift, covering a number-theory algorithm built on loops. This is for anyone searching for "Swift prime factorization implementation".

Prime factorization means expressing a number as a product of primes. Try dividing by 2, then 3, and so on; whenever a divisor works, keep dividing by it.

The sample code starts at d = 2 and, for as long as num divides by d, records it with factors.append(d) and divides with num /= d. When it no longer divides, d increases by one, repeating until num reaches 1.

A common stumbling block for beginners is the nested loop structure. The outer loop raises the divisor d while the inner loop keeps dividing for as long as it can - grasp that two-stage combination and the whole algorithm falls into place.

It is an important idea spanning mathematics and computer science that underpins the security of cryptography such as RSA. Since 1 divides everything, it is excluded from prime factorization.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)