javascript - Iterating using a quadratic sequence in Javascript
问题描述
I have a quadratic sequence in which I need to use to loop over, however, I am not sure how to execute this kind of logic... I want to use the quadratic sequence to count up to a given number <= n
. The problem is that I have to give my quadratic sequence for loop some number to count and iterate up to as well... I know it's possible to iterate by 2s, 3s, 4s, etc. by doing things like i += 2, is it possible to use a quadratic expression as well? Is there a method using Javascript in which will allow me to iterate through quadratic sequences? I hope this is clear, thanks!
Here's my code:
The quadratic sequence is the sequence being console logged. The first 14 terms are: 1,3,6,10,15,21,28,36,45,55,66,78,91,105
for (let i = 1; i <= 14; i++) {
let a = i;
let nthTerm = a - 1;
let b = 1 / 2;
let quadraticSequence = b * a ** 2 + b * a;
console.log(`${nthTerm} ${quadraticSequence}`);
const num = 93;
// use quadratic sequence to count up to a number <= 93;
for (i = 0; i <= num; i++quadraticSequence) {
console.log(i);
}
}
The result should console.log a count 0 > 105. I know the second for loop is not correct, but I'm not quite sure how to approach a proper attempt.
So instead of counting like, 1,2,3,4,5,6,7,8,9... It should count 1,3,6,10,15,21,28,36,45,55... Ultimately, I am trying to count up to a given number <= n (i.e. 93) through the quadratic sequence instead of the usually, 1,2,3,4,5, sequence.
解决方案
let num = 93;
for (let i = 1, j = 2; i < 100; i += j, j += 1) {
console.log(i);
for (let k = 0; k <= num; k += i) {
console.log(k);
}
}
This will produce the sequence 1, 3, 6, 10, 15, 21, 28, 36, ... and then use each of them in a seperate for loop as step size.
An alternative interpretation would be using the 0th element in the quadratic series as the first step size and the next element as the next step size, etc.
for (let i = 1, j = 2, k = 0; k < 1000; k += i, i += j, j += 1) {
console.log(`Current, step: ${k}, ${i}`);
}
This should do that
推荐阅读
- wix - 使用属性值的 WIX 自定义操作条件不起作用
- amazon-dynamodb - dynamodb 我需要多少读取容量单位
- ruby-on-rails - 需要帮助来建立模型之间的正确关联
- solidity - 如何正确将 SafeMath.sol 导入合约
- r - Smote - 选择 Perc_under 和 Perc_Over
- python - AttributError:“模块”没有属性
- mysql - 在 MYSQL 中如何用减法更新 GROUP BY
- asp.net-core - ClaimTypes.NameIdentifier 与 Microsoft GraphApi 用户 ID 有何关系
- google-cloud-platform - 是否可以仅在 GCP 上首次启动时运行启动脚本?
- php - 引导切换没有响应