Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 60 / 68

Testing whether a number is prime

This lesson covers testing for a prime number in Julia, with the aim of understanding a basic mathematical algorithm built on a loop.

Whether a number is prime — divisible only by 1 and itself — can be settled by testing divisibility from 2 up to its square root. If nothing divides it, it is prime.

The sample code loops over the range for i in 2:isqrt(n) and concludes the number is not prime the moment it finds an i where n % i == 0. Julia provides isqrt() specifically for an integer square root.

A common early stumble is the difference between sqrt() and isqrt(). isqrt() returns an integer, which makes it convenient to use straight in a range.

It is an important mathematical property that underlies cryptography, and there is a more advanced technique — the Sieve of Eratosthenes — for finding many primes efficiently at once.

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

๐Ÿงช This site can't compile or run Julia 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)