[英]How to find divisors of number on specified interval?
我想使用WHILE循環編寫一個簡單的程序,用它可以獲取所輸入數字的所有因數。
例如,您希望數字為30的所有除數:1、2、3、5、6、10、15、30。現在,您希望程序僅以5到10的間隔顯示數字,例如5、6和10。
到目前為止,我一直在嘗試使用FOR語句獲取所有除數,但沒有間隔,因此我被困住了,不知道如何在WHILE循環中也可以這樣做。
#include <iostream>
using namespace std;
int main() {
int input_number;
cin >> input_number;
cout << "All numbers are " << input_number << endl;
for (int i = 1; i <= input_number; i++) {
if (input_number % i == 0) {
cout << i << " ";
}
}
return 0;
}
另外感謝您的幫助。
為什么要在while
循環中執行此操作? for
絕對是這里循環的正確選擇。 通過以下方法可以很清楚地檢查所有除數:
for (int i = 1; i <= input_number; i++) { ... }
如果要向其添加一個更窄的窗口,則可以更改循環的邊界:
for (int i = lower_bound; i <= upper_bound; i++) { ... }
將其轉換為while
循環將只涉及將這些語句展開為:
int i = lower_bound;
while (i <= upper_bound) {
...
i++;
}
但這更容易出錯-如果您的循環主體中有一個continue
, i
將不會遞增。
在while
循環中解決此問題可能不像在for
循環中解決問題那樣簡單(或蠻力)。
考慮使用while
的這種循環再現:
int input_number;
std::cin >> input_number;
int i = 1; //Start trying to divide the input number by 1
int limit = input_number; //Termination condition for the loop
while(i < limit) {
if(input_number % i == 0) { //If divisible by i, both i and input_number/i are factors
std::cout << i << " " << input_number / i << " ";
}
++i; //Try dividing by the next integer
/*Set the limit to our latest input_number/i so we don't get duplicate
results (e.g. (5, 6) and (6, 5) for input_number = 30)*/
limit = input_number / i;
}
對於input_number = 30
,此循環僅運行5次迭代,而for
循環版本則運行30次迭代。
底線
for
循環和while
循環可以互換,但是使用for
循環解決問題可能比使用while
循環解決問題更快,反之亦然,因為它們可以幫助您從不同的角度思考問題。
額外的信息
for
循環版本允許某些優化技術,例如並行累加器,在while
循環版本中是不可能的,因為每次迭代都取決於前一個迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.