Alice and Bob's Silly Game

  • + 0 comments

    JavaScript Solution

    let ans = 0
        if (n === 1) return "Bob"
        else ans++      // because n>0
        function isPrime(i) {
    // optimal the loop condition
            let limit = Math.round(Math.sqrt(i)) 
            for (let mod = 2; mod <= limit; mod++) {
                if (i % mod === 0) {
                    return false;
                }
            }
            return true
        }
    // eleminate the even number except 2 to optimal the loop
        for (let i = 3; i <= n; i += 2) {   
            if (isPrime(i))
                ans++
        }
        return ans % 2 === 0 ? "Bob" : "Alice"