我創建了一個函式,可以將所有奇數 fibronacci 數相加到一個給定的數字,并且在大多數情況下,除了一個數字之外,它都適用。例如 sumFibs(10) 應該回傳 10 因為所有 Fib #s <= 10 是 1,1,3 和 5。
如果我做 sumFibs(75024); 我得到 135721 而不是預期值是 60696。對于其他每個數字,它都可以正常作業,我正在撓頭解決它
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x ) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; x < num; x ) {
if (cuntNuts < num) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts = thunderAss[x];
}
} else {
break;
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
uj5u.com熱心網友回復:
條件if (cuntNuts < num)不對。cuntNuts是斐波那契數的總和,而不是斐波那契數本身。因此,當總和達到 時,您將停止n,而不是將所有奇數相加到n。
您應該thunderAss[x]與num. <=如果該數字應包括在總數中,則應該如此。
您也可以將此條件放入for回圈標頭中,而不是將其作為單獨的檢查添加到正文中。
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x ) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; thunderAss[x] <= num; x ) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts = thunderAss[x];
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
uj5u.com熱心網友回復:
您正在添加第num一個斐波那契數,而不是小于或等于 的斐波那契數num。
在我的解決方案中,我做了正確的事情并得到了正確的答案:
function* fibonacci()
{
let x = 0;
let y = 1;
while (true) {
yield x;
[x, y] = [y, x y];
}
}
function sum_odd_fibonacci(max)
{
const fib_seq = fibonacci();
let s = 0;
let n;
while ( (n=fib_seq.next().value) <= max) {
if (n % 2 == 1) {
s = n;
}
}
return s;
}
console.log(sum_odd_fibonacci(75024));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424821.html
標籤:javascript 数组 功能 数学 斐波那契
