Example of common iteration

Saturday, December 16, 2017

常見Iterative式

  1. Factorial
  2. 最大公因數 GCD (Greatest Common Division)
  3. Fibonacci Number
  4. 1+2+3+…+n
  5. 1^2+2^2+3^2+…+n^2
  6. 1!+2!+3!+…+n!
  7. x^n

Iteration 疊代、跌代

定義:不斷利用目前求得的數值,再求得新數值,再用新數值繼續求得下一個新的值。

實作方式:使用迴圈(for、while、do-while)

Development Define Goal
Incremental staging and scheduling strategy improve your process
Iterative rework scheduling strategy improve your product

Iteration

1. Factorial

#include <stdio.h>
 
int main(void) {
	int i;
	int sum = 1, n;
	for(i = 1; i <= n; i++){
		sum *= i;
	}
	printf("%d", sum);
}

2. 最大公因數 GCD (Greatest Common Division)

#include <stdio.h>
 
int main(void) {
	int k; 
	int a, b;
	scanf("%d %d", &a, &b);
	while(a % b != 0){
		k = a % b;
		a = b;
		b = k;
	}
	printf("%d", b);
}

3. Fibonacci Number

#include <stdio.h>
 
int main(void) {
	int i = 0, n;
	int fib[n];
	fib[0] = 0;
	fib[1] = 1;
 
	scanf("%d", &n);
	for(i = 2; i <= n; i++){
		fib[i] = fib[i -1] + fib[i - 2];	
	}
	for(i = 2; i <= n; i++){
		printf("%d\n", fib[i]);
	}
}

4. 1+2+3+…+n

#include <stdio.h>
 
int main(void) {
	int i, n;
	int sum = 0;
	scanf("%d", &n);
	for(i = 1; i <= n; i++){
		sum += i;
	}
	printf("%d", sum);
}

5. 1^2+2^2+3^2+…+n^2

#include <stdio.h>
 
int main(void)
{
    int i, sum=0;
    int n;
    scanf("%d", &n);
 
    if(n <= 0) return 0;
    for(i = 0; i <= n; i++){
    	sum += i * i;
    }
    printf("%d", sum);
    return 0;
}

6. 1!+2!+3!+…+n!

#include <stdio.h>
int main(void) {
	int i = 0, n;
	int sum = 1, total = 0;
	scanf("%d", &n);
	for(i = 1; i <= n; i++){
		sum *= i;
		total += sum;
	}
	printf("%d", total);
}

7. x^n

#include <stdio.h>

/* Iteration : x ^ n */

int main(void) {
	int x;
	int i; // counter
	int n; // power
	int sum = 1;
	
	scanf("%d%d", &x, &n);
	
	for(i = 1; i <= n; i++){
		sum *= x;
	}
	printf("%d^%d is %d", x, n, sum);
	return 0;
}
ProgrammingC程式

AI_debate

Example of common recursion.