|
| 1 | +## Java implementation |
| 2 | + |
| 3 | +```Java |
| 4 | +static boolean isPrimeNumber(int number){ |
| 5 | + int zeroRemainderCount=0; |
| 6 | + for(int i=1; i <= number; i++){ |
| 7 | + if(number % i == 0) zeroRemainderCount++; |
| 8 | + } |
| 9 | + |
| 10 | + return zeroRemainderCount == 2 ? true : false; |
| 11 | +} |
| 12 | + |
| 13 | +# Example usage: |
| 14 | +System.out.println(isPrimeNumber(7)) # Output: true |
| 15 | +System.out.println(isPrimeNumber(12)) # Output: false |
| 16 | +``` |
| 17 | + |
| 18 | +## JavaScript implementation |
| 19 | + |
| 20 | +```javascript |
| 21 | +function isPrimeNumber(number){ |
| 22 | + let zeroRemainderCount = 0; |
| 23 | + for(i=0; i<=number; i++){ |
| 24 | + if(number % i === 0) zeroRemainderCount++; |
| 25 | + } |
| 26 | + return (zeroRemainderCount === 2) ? true : false; |
| 27 | +} |
| 28 | + |
| 29 | +// Example usage: |
| 30 | +console.log(isPrimeNumber(11)); // Output: true |
| 31 | +console.log(isPrimeNumber(81)); // Output: false |
| 32 | +``` |
| 33 | + |
| 34 | +## Explanation |
| 35 | + |
| 36 | +The Java implementation uses a function named `isPrimeNumber` that takes a single argument `number`. It returns `true` if the number is prime (e.g, when the zero remainder count of the division of the number by numbers between 1 and itself is two), otherwise, it returns `false`. |
| 37 | + |
| 38 | +The JavaScript implementation uses a function named `isPrimeNumber` that also takes a single argument `number`. It returns `true` if the number is prime (using the same logic as the Java function) and `false` otherwise. |
| 39 | + |
| 40 | +### Improvement in the Function Implementation: |
| 41 | +For large numbers, it will be reasonable to exit the loop once the zero remainder count reaches a value of 3. |
| 42 | + |
| 43 | +### Differences |
| 44 | + |
| 45 | +1. **Syntax**: |
| 46 | + - In Java, functions are defined by specifying the function name which is preceeded by the return type i.e `boolean isPrimeNumber`, whereas in JavaScript, the `function` keyword preeceds the function name i.e `boolean isPrimeNumber`. |
| 47 | + |
| 48 | + The loop variable `i` was initialize with a value 0 that is type-annotated `int` in Java implementation. However, in JavaScript implementation, the variable `i` was not type-annotated. |
| 49 | + |
| 50 | +2. **Equality Check**: |
| 51 | + - Java uses `double equal sign (==)` to test equality whereas JavaScript uses `tripple equal sign (===)` to test equality. |
| 52 | + |
| 53 | +3. **Function Calls**: |
| 54 | + - The syntax for calling functions and printing to the console/output is slightly different. Java uses `System.out.println() or System.out.print()`, while JavaScript uses `console.log()`. |
| 55 | + |
0 commit comments