Chapter 03 Control Flow
4.5 Examples of Iteration
The problems below might be easy, so try your best to make your solution easier and simpler.
Fibonacci
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int fib_1 = 1, fib_2 = 2; //the first two fibonacci number
for (int i = 3; i <= n; i++){
int temp = fib_1 + fib_2; //compute the next fibonacci number
fib_1 = fib_2; //remember last fibonacci number;
fib_2 = temp; //remember the new fibonacci number;
}
cout << "The " << n << "th fibonacci number is: " << fib_2 << "." << endl;
return 0;
}
The body for the iteration can also be written like this:
fib_2 = fib_1 + fib_2; fib_1 = fib_2 - fib_1;
Newton’s Iteration Method For Cubic Root of ‘a’
#include <iostream>
#include <cmath>
using namespace std;
int main(){
const double EPS = 1e-6; //EPS means epsilon, which is a very small number.
double a, x1, x2; //x1, x2 is used to store x(n) and x(n+1)
cout << "Please input a number: ";
cin >> a;
x2 = a; //the first number is a
do{
x1 = x2; //remember the previous number
x2 = (2 * x1 + a / (x1 * x1)) / 3; //compute the new number
} while (fabs(x1 - x2) >= EPS);
cout << a << "'s cubic rooy is " << x2 << " ." << endl;
return 0;
}
Output All the Prime Numbers No Larger Than ‘n’
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int n, count = 1;
cin >> n; //input a number from the keyboard
if (n <= 2) return -1;
cout << 2 << ", "; //cout the first prime number
for (int i = 3; i <= n; i += 2) { //even number can't be prime number, so we just need to test the odd numbers.
int j = 2, k = (int)sqrt((double)i); //we don't need to test every number less than i, try everything to make the steps less
while (j <= k && i % j != 0) j++;
if (j > k) {
cout << i << ", ";
count ++;
if (count % 6 == 0) cout << endl; //make sure each line have 6 numbers
}
}
cout << endl;
return 0;
}
Sum 1 + x + x^2/2! + x^3/3! + x^4/4! + … + x^n/n!
#include <iostream>
using namespace std;
int main(){
double x;
int n;
cin >> x >> n;
double item = x, //item is used to store each item of the series
sum = 1 + x; //sum stores the sum, initialized as the summation od the first two items
for (int i = 2; i < n; i++){ //compute each item and add them to the sum
item *= x / i; //compute the next item
//inatead of compute the factorial and power separately, using recursion is more convenient
sum += item;
}
cout << "x = " << x << ", n = " << n << ", sum = " << sum << endl;
return 0;
}