# 迴圈應用
a041-a045
---
迴圈重要觀念
1. 起始點
2. 終點
3. 每一圈的變化
---
a041 收集冰棒棍
tcgs.tc.edu.tw:1218/ShowProblem?problemid=a041
----
思考
用手算會怎麼算
----
輸入5 5-5=0 0+1=1
吃掉5 5+1=6
輸入9 9-5=4 4+1=5 5-5=0 0+1=1
吃掉9 9+1=10 10+1=11
----
用兩個變數存
a為當前冰棒棍數 b為吃了幾支
```cpp
int a;
cin >> a;
int b = a;
while(a>4){
a -= 4;
b ++;
}
cout << b;
```
---
a042 13的次方
tcgs.tc.edu.tw:1218/ShowProblem?problemid=a042
----
其實是數學問題
----
只要算十位數 亦即百位以上之數可忽略
每層迴圈都將運算的結果mod100
----
這題很簡單 請嘗試過再往下看解答
----
```cpp
int a;
cin >> a;
int b = 1;
for(int i = 0;i<a;i++){
b *= 13;
b %= 100;
}
cout << b/10;
```
---
a043 最大公因數
tcgs.tc.edu.tw:1218/ShowProblem?problemid=a043
----
輾轉相除法
----
20 12 最大公因數
20%12=8
12%8=4
8%4=0
用兩個變數即可達成
----
t用來暫存m%n之值
終止條件為m%n==0
以上一頁為例 8%4=0 此時t=0 m=8 n=4
但上一層迴圈已經執行 m=n n=t 了
因此最大公因數為當前的m
----
```cpp
int m,n,t;
cin >> m >> n;
int t = 1;
while(t){//t!=0
t = m%n;
m = n;
n = t;
}
cout << m;
```
---
a044 盈數、虧數和完全數
tcgs.tc.edu.tw:1218/ShowProblem?problemid=a044
----
從1數到值 只要整除就是因數
----
這題超簡單 自己寫
---
a045 質數判斷
tcgs.tc.edu.tw:1218/ShowProblem?problemid=a045
----
從一數到值 沒有因數就是質數
哇 這題根本送分題吧
----
前三測資過了 後兩測資TLE
----
其實如果有大於${\sqrt n}$的因數
就一定會有小於${\sqrt n}$的因數
----
因此中止條件定為${\sqrt n}$就好了
```cpp
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int a;
cin >> a;
for(int i = 2;i<=sqrt(a);i++){//不能只寫小於
if(!a%i){//a%i==0 不然平方數過不了
cout << "NO";
return 0;//中止main()
}
}
cout << "YES";
}
```
{"metaMigratedAt":"2023-06-15T02:48:35.956Z","metaMigratedFrom":"YAML","title":"迴圈應用","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"9f6a1b41-e592-4580-9e63-5613e2cac6cb\",\"add\":1635,\"del\":21}]"}