|
| 1 | +## Java implementation |
| 2 | + |
| 3 | +```java |
| 4 | +public class PrimeCheck { |
| 5 | + public static boolean isPrime(int n) { |
| 6 | + if (n < 2) return false; |
| 7 | + for (int i = 2; i <= Math.sqrt(n); i++) { |
| 8 | + if (n % i == 0) return false; |
| 9 | + } |
| 10 | + return true; |
| 11 | + } |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + int number = 29; |
| 15 | + System.out.println(number + " is prime? " + isPrime(number)); |
| 16 | + } |
| 17 | +} |
| 18 | +``` |
| 19 | + |
| 20 | +## TypeScript implementation |
| 21 | + |
| 22 | +```TypeScript |
| 23 | +function isPrime(n: number): boolean { |
| 24 | + if (n < 2) return false; |
| 25 | + for (let i = 2; i <= Math.sqrt(n); i++) { |
| 26 | + if (n % i === 0) return false; |
| 27 | + } |
| 28 | + return true; |
| 29 | +} |
| 30 | + |
| 31 | +const number = 29; |
| 32 | +console.log(`${number} is prime? ${isPrime(number)}`); |
| 33 | +``` |
| 34 | + |
| 35 | +## Explanation |
| 36 | + |
| 37 | +The Java implementation uses a function named 'isPrime' that is defined inside a 'class'. It takes a single integer as input and returns 'true' if the number is prime (i.e., greater than 1 and not divisible by any number other than 1 and itself). Otherwise, it returns 'false'. |
| 38 | + |
| 39 | +The TypeScript implementation also defines a function named 'isPrime' that accepts a number as input. It uses the same mathematical logic as the Java function, returning 'true' when the number is prime and 'false' otherwise. |
| 40 | + |
| 41 | +### Differences |
| 42 | + |
| 43 | +1. **Syntax**: |
| 44 | + |
| 45 | + -In Java, functions must be defined inside a class, and you must also create a 'main' method to run the program. |
| 46 | + -In TypeScript, functions can be written directly without needing a 'class' or a special entry point. |
| 47 | + |
| 48 | +2. **Types**: |
| 49 | + -Java requires explicit type declarations ('int' for integers, 'boolean' for return values). |
| 50 | + -TypeScript also uses types, but the syntax is lighter (e.g., 'n: number' instead of 'int n'). |
| 51 | + |
| 52 | +3. **Structure**: |
| 53 | + -Java enforces more boilerplate code, such as the 'public class' and 'public static' keywords. |
| 54 | + -TypeScript feels closer to JavaScript and allows quicker setup with just the function and a 'console.log' statement. |
0 commit comments