Last digit of power list

前端 未结 3 1555
忘掉有多难
忘掉有多难 2020-12-29 11:21

Outline of problem:

Please note I will abuse the life out of ^ and use it as a power symbol, despite the caret symbol being the bitwise

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 11:59

    Finally! after doing some digging about I realized I can modify the initial idea and get the answer I wanted:

    let LD = (as) =>
      as.reduceRight((acc, val) =>
        Math.pow(val < 20 ? val : (val % 20 + 20), acc < 4 ? acc : (acc % 4 + 4)) 
      , 1) % 10
    

    Tests:

    let LD = (as) =>
      as.reduceRight((acc, val) =>
        Math.pow(val < 20 ? val : (val % 20 + 20), acc < 4 ? acc : (acc % 4 + 4)) 
      , 1) % 10
    
    let LDTest = (array, expected) => 
      console.log((LD(array) === expected ? "Success" : "Failed"), 
        "for", array, "got", LD(array), "expected", expected);
    
    LDTest([ 2, 2, 2 ],    6)
    LDTest([ 2, 2, 2, 2 ], 6)
    LDTest([ 3, 4, 5 ],    1)
    LDTest([ 6, 8, 10 ],   6)
    LDTest([ 2, 2, 0 ],    2)
    LDTest([ 12, 30, 21 ], 6) 
    LDTest([ 0, 0 ],       1) // x^0 === 1 
    LDTest([ 0 ],          0)  

    So why modulo 20? Because a modulus of 10 loses precision in the cases such as [ 2,2,2,2 ], when we hit the last step as from the question example:

    Fourth iteration, where the issue becomes apparent. a = 6, v = 2:

    p[2 % 10][(6-1) % p[2 % 10].length]

    = [ 2,4,8,6 ][5 % 4]

    = 4

    Easily disproved by 2 ^ 16 = 65536.

    By simply allowing a multiple up to 20, we have the LCM (lowest common multiple) for each count of the array, as well as for the length of p, which is 10. (LCM([ 1,2,4,10 ]) === 20).

    However, as the exponential is now never higher than 40^8 (approximately 6 trillion), and as it is taken to the modulo of 4 in the next iteration, we can simply do the exponential and return the answer each time.

    Of course to get the digit in the final case, we need to take modulo of 10 to just return that last digit.


    There's still some stuff I'm not understanding here.

    We allow any value under the modulo value to retain its value with the ternary operators. E.g., for the exponent, prev < 4 ? prev : (prev % 4 + 4). However I initially believed this to be prev === 0 ? 0 : (prev % 4 + 4).

    This is because th exponent of zero does not have the same ending digit as the other multiples of the modulo, it always equals 1 (x ^ 0 === 1). So, by adding 4, we get a value that does have the same last digit, and by leaving zero alone we still get 1 for zero exponents.

    Why is it that prev < 4 ? prev : (prev % 4 + 4) was required to make this answer correct? Why is e.g., prev = 3, need to be 3 instead of adding 4 like the others?

提交回复
热议问题