-1

May be the question is so clear and doesn't need any more explanation but this is examples previous primes:

The previous prime of 19 is ===> 17
The previous prime of 211 is===> 199

My failing trial

const getPreviousPrime = (number) => {
    for(let i = number - 1; i >= 2; i--) {
       for(let j = 2; j <= Math.sqrt(i); j++ ) {
          if(i % j === 0) break
          return i
      }

    }
}
Code Eagle
  • 1,293
  • 1
  • 17
  • 34
  • 1
    Show an example where your trial is wrong. Then figure out what exactly your code does in that example, and you'll probably solve this question yourself. – Brilliand Jul 09 '20 at 20:58
  • my code just abstract 2 from the original number – Code Eagle Jul 09 '20 at 21:00
  • 2
    What's with `j <= 9` ? Shouldn't it be `j <= Math.sqrt(i)`. – James Jul 09 '20 at 21:00
  • Might be helpful to start with a prime number algorithm, and work your way back from there. – dwb Jul 09 '20 at 21:01
  • @James thanks james but still i have the same problem – Code Eagle Jul 09 '20 at 21:04
  • This feels like homework, so I don't think we *should* give an exact right answer. Nonetheless, I see a deleted answer pointing out that your return statement is in the wrong place; that's one of your problems. – Brilliand Jul 09 '20 at 21:06
  • @Brilliand it is not a homework, and i am struggling here for 1 hour trying to solve it, not all people starts good – Code Eagle Jul 09 '20 at 21:08

2 Answers2

5

Start by writing assuming you have an isPrime() function.

Then you can write the loop easily.

const getPreviousPrime = (number) => {
  for (let i = number - 1; i >= 2; i--) {
    if (isPrime(i)) {
      return i;
    }
  }
}

You can find many implementations of isPrime() at Number prime test in JavaScript

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

Hope this will help you.

const getPreviousPrime = (number) => {
    for(let i = number - 1; i >= 2; i--) {
        let prime = true;
        for(let j = 2; j <= Math.sqrt(i); j++ ) {
            if(i % j === 0) {
                prime = false
                break;
            }
        }
        if (prime == true) {
            return i
        }
    }
    return 2;
}

console.log(getPreviousPrime(19))
console.log(getPreviousPrime(211))
fro
  • 402
  • 3
  • 8