I want a very short code (maximum 6 lines code) for identifying the given input is prime number or not ???

Dani AI

Generated

Building on the suggestions from (limit checks to sqrt(n)) and (loop with modulo), the following is a compact VB.NET implementation that handles common edge cases and stays within six lines:

Function IsPrime(n As Long) As Boolean
    If n < 2 Then Return False : If n = 2 Then Return True : If n Mod 2 = 0 Then Return False
    For i As Long = 3 To CLng(Math.Floor(Math.Sqrt(n))) Step 2 : If n Mod i = 0 Then Return False : Next
    Return True
End Function

Notes and cautions:

  • Early exits cover n < 2, n = 2 and even numbers, reducing work before the loop. The loop checks only odd divisors up to floor(sqrt(n)), so complexity is O(sqrt(n)).
  • Declaring i As Long and using CLng keeps the bounds consistent with n As Long. If using classic VB (VB6), replace Math.Floor(Math.Sqrt(n)) with Int(Sqr(n)).
  • For very large values (many digits) or cryptographic needs, switch from trial division to proven primality tests (e.g., Miller–Rabin or deterministic algorithms) and use BigInteger-like libraries (System.Numerics.BigInteger) to avoid overflow and performance issues.

Recommended Answers

All 3 Replies

We're not going to write it for you.

You should already know that a prime number is a number that is only divisible by 1 and itself.

So, the most trivial way to check if p is prime is to check to make sure it's not divisible by any number from 1 to p. This will work fine.

We can make it faster by considering that if a number is divisible by 2, then it would be disivible by 4, 6, 8, etc, so we only need to check 2 and odd numbers.

We can futher make it faster by considering for each number we check under the square-root, we are also checking the dividand above the square root. Thus, we only need to check numbers from 2 to sqrt(n).

This is probably the fastest you'll get out of a 6 line implementation without getting too fancy.

One of the quickest ways is to check if n divided by 2....sqrt(n) results in an even number. If any of them do the number is not prime.
so:
detemine square root of n (rounded up)

loop through 2 to square root of n, dividing n by number. If even division occurs (modulo) n is not prime.

Thanks for the reply !!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.