我有一个整数X和X的所有因子的列表。我想输出X和因子之间的比率,并且每次将X设置为该比率。我希望这个算法继续,直到比率大于或等于1.
例如:X = 36。
所有因素(但1和36):2,3,4,6,9,12,18,
算法:36/2 = 18 - > 18/3 = 6 - > 6/4 = 1.5 - > 1.5 / 6< 1 - >停止
输出:[18,6,1.5]。问题:
如何获得此输出?
我写的:
var arr = [];
for (var i = 2; i < X; i++) {
if (X % i == 0) {
arr.push(i);
}
}
var temp = [];
var index = 0;
while (X / arr[index] >= 1) {
index += 1;
X = X / arr[index];
temp.push(X / arr[index]);
}
答案 0 :(得分:0)
您可以在进入while循环之前计算第一个值并检查asssigned x
。如果值超过条件,则可以将该值推送到结果数组并增加索引并计算新值。
function fn(x) {
var array = [], // declare all variable on top
i,
result = [];
for (var i = 2; i < x; i++) {
if (x % i == 0) {
array.push(i);
}
}
i = 0; // prepare index for looping
x /= array[i]; // take a first possible value
while (x >= 1) { // check value
result.push(x); // push value
i++; // increment index
x /= array[i]; // take the next value for checking
}
return result;
}
console.log(fn(36))
&#13;
稍短
function fn(x) {
var array = [], // declare all variable on top
i,
result = [];
for (var i = 2; i < x; i++) {
if (x % i == 0) {
array.push(i);
}
}
array.every(v => (x /= v) >= 1 && result.push(x));
return result;
}
console.log(fn(36))
&#13;
答案 1 :(得分:0)
var arr = [];
var X = 36
for (var i = 2; i < X; i++) {
if (X % i == 0) {
arr.push(i);
}
}
var temp = arr.reduce((acc, item, index) => {
if(!(X/item < 1)){
acc.push(X/item)
X = X/item;
}
return acc;
}, [])
console.log(temp)
&#13;
答案 2 :(得分:0)
你的问题有点混乱。这是你想要的吗?
基本上,我在每次迭代后更新因子(如果&gt; = 1)并将输出存储到数组中。
// Generate a range of integers (starting at 2, and we should not including the input)
// get only values divisible by the input (filter)
const generateRange = (input) => {
return Array.from({length: (input - 2)}, (v, k) => k + 2).filter(i => {
return input % i === 0;
})
}
const divideFactors = (input) => {
const list = generateRange(input) // filtered range
let output = []
let factor = input
for (const item of list) {
let ratio = factor / item
if (ratio < 1) { //if ratio < 1, break the loop
break;
}
output.push(ratio) // update output array with new ratio
factor = ratio; // update factor variable with current ratio
}
return output
}
console.log(divideFactors(36))
&#13;
更多信息:
Array.from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
适用于: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of