Thuật toán cơ bản:
Code C++:
#include<bits/stdc++.h> using namespace std; int main() { int i, n; long S; S = 0; i = 1; cout << " Nhap n : "; cin >> n; while(i <= n) { S = S + i; i++; } cout << S; return 0; }
Thuật toán tối ưu:
#include<bits/stdc++.h> using namespace std; int main() { int n, S; S=0; cout << " Nhap n : "; cin >> n; S += n*(1+n)/2; cout << s; return 0; }