Advertisement
Spocoman

08. Numbers, Divisible by 9

Dec 23rd, 2021 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function numbersDivisibleOf9(input) {
  2.     let startNum = Number(input[0]);
  3.     let finalNum = Number(input[1]);
  4.     let numbers = '';
  5.     let sum = 0;
  6.  
  7.     for (let i = startNum; i <= finalNum; i++) {
  8.         if (i % 9 === 0) {
  9.             sum += i;
  10.             numbers += i + '\n';
  11.             i += 8;
  12.         }
  13.     }
  14.     console.log(`The sum: ${sum}\n${numbers}`);
  15. }
  16.  
  17. РЕШЕНИЕ С МАСИВ И ЛАМБДА:
  18.  
  19. function numbersDivisibleOf9(input) {
  20.     let startNum = Number(input[0]);
  21.     let finalNum = Number(input[1]);
  22.     let numbers = [];
  23.  
  24.     for (let i = startNum; i <= finalNum; i++) {
  25.         if (i % 9 === 0) {
  26.             numbers.push(i);
  27.             i += 8;
  28.         }
  29.     }
  30.     console.log(`The sum: ${numbers.reduce((a, b) => a + b, 0)}\n${numbers.join('\n')}`);
  31. }
  32.  
  33. ИЛИ:
  34.  
  35. function numbersDivisibleOf9(input) {
  36.     let startNum = Number(input[0]);
  37.     let finalNum = Number(input[1]);
  38.    
  39.     let numbers = Array(finalNum - startNum + 1).fill().map((_, i) => startNum + i).filter(n => n % 9 === 0);
  40.     console.log(`The sum: ${numbers.reduce((a, b) => a + b, 0)}\n${numbers.join('\n')}`);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement