简体   繁体   中英

A Rule of Divisibility by 7 - Codewars Javascript Challenge

For this codewars challenge

The following code passes tests but it's experiencing a timeout error:

 function seven(m) { let count = 0; m = String(m); while (Number(m.slice(0, m.length - 1)) - (Number(m[m.length - 1]) * 2) % 7 !== 0) { let first = Number(m.slice(0, m.length - 1)); let second = Number(m[m.length - 1]) * 2; m = first - second; count++; m = String(m); } return [Number(m), count]; } console.log(seven(483)); 

As I understand, the idea is to continue breaking a number down until it's divisible by 7. Stop when the number has at most 2 digits.

A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a number known to be divisible or not by 7 is obtained; you can stop when this number has at most 2 digits because you are supposed to know if a number of at most 2 digits is divisible by 7 or not.

The original number is divisible by 7 if and only if the last number obtained using this procedure is divisible by 7.

Example :

1 - m = 371 -> 37 − (2×1) -> 37 − 2 = 35 ;

thus, since 35 is divisible by 7, 371 is divisible by 7.

And I'm not sure how else to optimize this code. Perhaps I'm misunderstanding the question and that's why my while-loop is overly complicated. Any suggestions?

EDIT - second attempt - trying to avoid converting to String and back to Number:

 function seven (m) { let count = 0; while ((String(m).length > 2) && (m % 7 !== 0)) { let last = (m % 10); let first = (m - last) / 10; m = (first - (last * 2)); count++; } return [m, count]; } 

This is passing 84 tests, failing 26.

You can just compute the input until it is smaller than 3 digits and return the count.

Please try this:

function seven(m) {    
  let count = 0;

  while(m > 99) {
    m = parseInt(m / 10) - (2 * (m % 10)); 
    count++;
  }

  return [m, count];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM