Skip to content

Instantly share code, notes, and snippets.

@coltenkrauter
Created July 11, 2023 19:20
Show Gist options
  • Save coltenkrauter/da4bd954adf51f4dd65a2fc2378775d2 to your computer and use it in GitHub Desktop.
Save coltenkrauter/da4bd954adf51f4dd65a2fc2378775d2 to your computer and use it in GitHub Desktop.
Function to match Prime numbers Java/JavaScript/Python

TypeScript

// Using ECMAScript 6 repeat function
const isPrime = (n: number): boolean => {
    let re = /^.?$|^(..+?)\1+$/;
    return !re.test('1'.repeat(n));
}

JavaScript

// Using ECMAScript 6 repeat function
const isPrime = (n) => {
    let re = /^.?$|^(..+?)\1+$/;
    return !re.test('1'.repeat(n));
}

const isPrime = (n) => {
    let re = /^.?$|^(..+?)\1+$/;
    return !re.test(Array(n + 1).join('1'));
}

Java

public static boolean isPrime(int n) {
    return !new String(new char[n]).matches(".?|(..+?)\\1+");
}

Python

import re

def is_prime(n):
    return not re.match(r'^.?$|^(..+?)\1+$', '1' * n)

Credits

https://iluxonchik.github.io/regular-expression-check-if-number-is-prime/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment