To check if number is a prime in C# and VB.NET you can use the follwing snippet.

Sample C#

{
	var sqrtBound = Math.Floor(Math.Sqrt(input));

	if (input == 1)
	{
		return false;
	}
	if (input == 2)
	{
		return true;
	}

	for (var i = 2; i <= sqrtBound; ++i)
	{
		if (input%i == 0)
		{
			return false;
		}
	}

	return true;
}

Sample VB.NET

Public Shared Function IsPrime(input As Integer) As Boolean
	Dim sqrtBound = Math.Floor(Math.Sqrt(input))

	If input = 1 Then
		Return False
	End If
	If input = 2 Then
		Return True
	End If

	For i As var = 2 To sqrtBound
		If input Mod i = 0 Then
			Return False
		End If
	Next

	Return True
End Function

One thought on “How to check if number is a prime in C# and VB.NET”

Leave a Reply