Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 60 / 68

Testing whether a number is prime

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

A prime is an integer of 2 or more divisible only by 1 and itself. An IsPrime() function settles it efficiently by testing divisibility from 2 up to the square root.

The sample code loops over For i As Integer = 2 To Math.Sqrt(n) and concludes the number is not prime the moment it finds an i where n Mod i = 0. Checking only as far as the square root works because any larger divisor is necessarily paired with a smaller one.

A common early stumble is why the square root is enough. Testing every number below n also gives the right answer, but stopping at the square root removes a great deal of wasted work.

Primality testing underpins mathematics used in real security work — cryptography, hash functions.

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

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