{"id":1025,"date":"2026-10-30T12:15:59","date_gmt":"2026-10-30T12:15:59","guid":{"rendered":"https:\/\/blog.debuggersspace.com\/?p=1025"},"modified":"2026-10-30T14:13:21","modified_gmt":"2026-10-30T14:13:21","slug":"write-a-program-to-check-whether-a-number-is-prime-then-make-it-faster","status":"publish","type":"post","link":"https:\/\/blog.debuggersspace.com\/index.php\/2026\/10\/30\/write-a-program-to-check-whether-a-number-is-prime-then-make-it-faster\/","title":{"rendered":"Write a program to check whether a number is prime, then make it faster."},"content":{"rendered":"<div class='booster-block booster-read-block'>\n                <div class=\"twp-read-time\">\n                \t<i class=\"booster-icon twp-clock\"><\/i> <span>Read Time:<\/span>2 Minute, 46 Second                <\/div>\n\n            <\/div>\r\n<p class=\"wp-block-paragraph\">A prime number is a whole number greater than 1 whose only divisors are 1 and itself. This question is common in the TCS NQT coding section and the technical interview because it tests whether you can write correct code first and then improve it step by step.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Step 1: the simple version (O(n))<\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Try every number from 2 to n \u2212 1. If any of them divides n, it is not prime.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>static boolean isPrimeSlow(int n) {\r\n    if (n &lt; 2) return false;\r\n    for (int i = 2; i &lt; n; i++) {\r\n        if (n % i == 0) return false;\r\n    }\r\n    return true;\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">It is correct but slow: for a prime near one billion it does a billion divisions.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Step 2: stop at the square root (O(\u221an))<\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">If n = a \u00d7 b and both a and b were bigger than \u221an, their product would be bigger than n. So at least one divisor is \u2264 \u221an, and you only need to check up to there. Write the condition as <code>i &lt;= n \/ i<\/code> instead of <code>i * i &lt;= n<\/code> so that <code>i * i<\/code> can never overflow an <code>int<\/code>.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>static boolean isPrime(int n) {\r\n    if (n &lt; 2) return false;\r\n    for (int i = 2; i &lt;= n \/ i; i++) {\r\n        if (n % i == 0) return false;\r\n    }\r\n    return true;\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Step 3: skip even numbers and multiples of 3<\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">After handling 2 and 3, every prime is of the form 6k \u2212 1 or 6k + 1. So you can test only 5, 7, 11, 13, 17, 19 and so on, which is about a third of the checks of step 2.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>static boolean isPrimeFast(int n) {\r\n    if (n &lt; 2) return false;\r\n    if (n &lt; 4) return true;               \/\/ 2 and 3\r\n    if (n % 2 == 0 || n % 3 == 0) return false;\r\n    for (int i = 5; i &lt;= n \/ i; i += 6) {\r\n        if (n % i == 0 || n % (i + 2) == 0) return false;\r\n    }\r\n    return true;\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Time is still O(\u221an), but with a much smaller constant. Space is O(1).<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Test cases to say out loud<\/h2>\r\n\r\n\r\n\r\n<ul class=\"wp-block-list\">\r\n<li>0, 1 and negative numbers: not prime.<\/li>\r\n\r\n\r\n\r\n<li>2 and 3: prime (the loop never runs).<\/li>\r\n\r\n\r\n\r\n<li>4, 9, 25, 49: squares of primes, which catch an off-by-one in the loop condition.<\/li>\r\n\r\n\r\n\r\n<li>2147483647 (the largest int, and a prime): checks there is no overflow.<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Follow-up: all primes up to N (Sieve of Eratosthenes)<\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">If the interviewer asks for every prime up to N, calling <code>isPrime<\/code> N times costs O(N\u221aN). The sieve does it in O(N log log N): start with every number marked prime, and for each prime p cross out p\u00b2, p\u00b2 + p, p\u00b2 + 2p and so on.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>static List&lt;Integer&gt; primesUpTo(int n) {\r\n    boolean[] composite = new boolean[n + 1];\r\n    List&lt;Integer&gt; primes = new ArrayList&lt;&gt;();\r\n    for (int p = 2; p &lt;= n; p++) {\r\n        if (composite[p]) continue;\r\n        primes.add(p);\r\n        for (long m = (long) p * p; m &lt;= n; m += p) composite[(int) m] = true;\r\n    }\r\n    return primes;\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\">Common mistakes<\/h2>\r\n\r\n\r\n\r\n<ul class=\"wp-block-list\">\r\n<li>Returning true for 1.<\/li>\r\n\r\n\r\n\r\n<li>Writing <code>i &lt; Math.sqrt(n)<\/code> instead of <code>&lt;=<\/code>, which calls 25 or 49 prime.<\/li>\r\n\r\n\r\n\r\n<li>Calling <code>Math.sqrt<\/code> on every loop iteration.<\/li>\r\n\r\n\r\n\r\n<li>Forgetting to say the time and space complexity at the end.<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\"><em>This answer was written by Debugger&#8217;s Space as practice material. See <a href=\"https:\/\/www.debuggersspace.com\/companies\/tata-consultancy-services-tcs\">how TCS hires, step by step, and more TCS practice questions<\/a>.<\/em><\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>Check whether a number is prime in Java: the simple version, the square-root version, skipping even numbers, the 6k \u00b1 1 trick, and the Sieve of Eratosthenes for many numbers.<\/p>\n","protected":false},"author":43,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","footnotes":""},"categories":[243],"tags":[270,264,290,228,277],"class_list":["post-1025","post","type-post","status-publish","format-standard","hentry","category-tcs-interview-preparation","tag-coding-interview-questions","tag-java-interview-questions","tag-prime-numbers","tag-tcs","tag-tcs-nqt"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Himanshu Namdeo","author_link":"https:\/\/blog.debuggersspace.com\/author\/admin\/"},"uagb_comment_info":0,"uagb_excerpt":"Check whether a number is prime in Java: the simple version, the square-root version, skipping even numbers, the 6k \u00b1 1 trick, and the Sieve of Eratosthenes for many numbers.","_links":{"self":[{"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/1025","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/users\/43"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/comments?post=1025"}],"version-history":[{"count":1,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/1025\/revisions"}],"predecessor-version":[{"id":1029,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/1025\/revisions\/1029"}],"wp:attachment":[{"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/media?parent=1025"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/categories?post=1025"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.debuggersspace.com\/index.php\/wp-json\/wp\/v2\/tags?post=1025"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}