Create a function named divisors
/Divisors
that takes an integer and returns an array with all of the integer‘s divisors(except for 1 and the number itself). If the number is prime return the string ‘(integer) is prime‘ (null
in C#) (use Either String a
in Haskell and Result<Vec<u32>, String>
in Rust).
Example:
divisors(12); // should return [2,3,4,6]
divisors(25); // should return [5]
divisors(13); // should return "13 is prime"
方法一
1 function divisors(integer) { 2 var arr = []; 3 for(var i = 2; i < integer; i++){ 4 if(integer % i ===0){ 5 arr.push(i);} 6 } 7 if(arr.length ===0){ 8 return integer+‘ is prime‘; 9 }else{ 10 return arr;} 11 };
上面方法不够完美,for循环里面 i <integer ,有重复,可以用如下方法,更简洁方法二
1 function divisors(integer) { 2 var arr = []; 3 for (var i = 2; i <= Math.floor(integer / 2); ++i) 4 if (integer % i === 0) arr.push(i); 5 return arr.length ? arr : integer + ‘ is prime‘; 6 };
Integer's divisors 关于整数的约数
时间: 2024-10-10 18:23:02