How to use Two Pointer Approach In Javascript
The Two Pointer Approach involves using two pointers, one starting from the smallest prime (2) and the other from the given number. While incrementing the first pointer and decrementing the second, it checks if their sum equals the target number.
Example: In this example The code generates prime numbers using the Sieve of Eratosthenes. `isPossible` function checks if a prime can be expressed as the sum of two other primes using a two-pointer approach.
Javascript
function generatePrimes(n) { let isPrime = new Array(n + 1).fill( true ); let primes = []; for (let i = 2; i <= n; i++) { if (isPrime[i]) { primes.push(i); for (let j = i * i; j <= n; j += i) { isPrime[j] = false ; } } } return primes; } function isPossible(n) { let primes = generatePrimes(n); let left = 0; let right = primes.length - 1; // Two-pointer approach while (left <= right) { let sum = primes[left] + primes[right]; if (sum === n) { return true ; } else if (sum < n) { left++; } else { right--; } } return false ; } const testCase1 = 7; console.log(isPossible(testCase1)); const testCase2 = 19; console.log(isPossible(testCase2)); |
true true
JavaScript Program to check Whether a Number can be Express as Sum of Two Prime Numbers
To check if a number can be expressed as the sum of two prime numbers, iterate through primes less than or equal to half of the given number. For each prime, check if the complementary prime exists by subtracting it from the target number and testing if the result is prime. If found, the number can be expressed as the sum of two primes.
There are several methods in JavaScript using which one can check whether a number can be expressed as a sum of two prime numbers which are as follows:
Table of Content
- Using for loop
- Using Two Pointer Approach