alboig

LeastMajorityPrinciple - JavascriptModule0

Apr 14th, 2020
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Least Majority Multiple
  2. // Given five positive integers, their least majority multiple is the smallest positive integer that is divisible by at least three of them.
  3. // Your task is to write a program that for given distinct integers a, b, c, d and e, returns their least majority multiple.
  4. // For example if we have 1, 2, 3, 4 and 5 the majority multiple of the given five numbers is 4 because it is divisible by 1, 2, and 4.
  5. // Another example: if we have 30, 42, 70, 35 and 90 the answer will be 210, because it is divisible by 30, 42, 70, and 35 - four out of five numbers, which is a majority.
  6. // Input
  7. // Read from the standard input
  8. // The input data will consist of 5 lines.
  9. // The numbers a, b, c, d and e will each be on a single line.
  10. // The input data will always be valid and in the format described. There is no need to check it explicitly.
  11. // Output
  12. // Print on the standard output
  13. // On the only output line you must print the least majority multiple of the given numbers.
  14. // Constraints
  15. // a, b, c, d and e will each be integer numbers between 1 and 100, inclusive.
  16. // a, b, c, d and e will be distinct.
  17. // Sample Tests
  18. // Input Output
  19. // 1
  20. // 2
  21. // 3
  22. // 4
  23. // 5 4
  24. // 30
  25. // 42
  26. // 70
  27. // 35
  28. // 90 210
  29. // JavaScript
  30. // Credit to https://www.w3resource.com/javascript-exercises/javascript-math-exercise-10.php
  31. const input = ['1', '2', '3', '4', '5'];
  32. const print = this.print || console.log;
  33. const gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
  34. const numArray = [];
  35. for (let i = 0; i < 5; i++) {
  36.   numArray.push(+gets());
  37. }
  38. numArray.sort((a, b) => a - b);
  39.  
  40. function gcdTwoNumbers (x, y) {
  41.   x = Math.abs(x);
  42.   y = Math.abs(y);
  43.   while (y) {
  44.     const t = y;
  45.     y = x % y;
  46.     x = t;
  47.   }
  48.   return x;
  49. }
  50.  
  51. function lcmTwoNumbers (x, y) {
  52.   if ((typeof x !== 'number') || (typeof y !== 'number')) {
  53.     return false;
  54.   }
  55.   return (!x || !y) ? 0 : Math.abs((x * y) / gcdTwoNumbers(x, y));
  56. }
  57.  
  58. function lcm3 (x, y, z) {
  59.   return lcmTwoNumbers(lcmTwoNumbers(x, y), z);
  60. }
  61. const a = numArray[0];
  62. const b = numArray[1];
  63. const c = numArray[2];
  64. const d = numArray[3];
  65. const e = numArray[4];
  66. print(Math.min(lcm3(a, b, c), lcm3(a, b, d), lcm3(a, b, e), lcm3(a, c, d), lcm3(a, c, e), lcm3(a, d, e), lcm3(b, c, d), lcm3(b, c, e), lcm3(b, d, e), lcm3(c, d, e)));
Advertisement
Add Comment
Please, Sign In to add comment