fork(3) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<class T>
  5. T sum_of_n (T n) {
  6. T total = 0;
  7. for (T i = 1; i <= n; ++i) total += i;
  8. return total;
  9. }
  10.  
  11. unsigned int sum_of_n_formula(unsigned int n) {
  12. return n * (n + 1) / 2;
  13. }
  14.  
  15. int main() {
  16. // no overflow
  17. cout << sum_of_n<unsigned int>(1000) << endl;
  18. cout << sum_of_n<int>(1000) << endl;
  19. cout << sum_of_n_formula(1000) << endl;
  20. // overflow
  21. cout << sum_of_n<unsigned int>(1000000000) << endl;
  22. cout << sum_of_n<int>(1000000000) << endl;
  23. cout << sum_of_n_formula(1000000000) << endl;
  24. return 0;
  25. }
Success #stdin #stdout 0.98s 5504KB
stdin
Standard input is empty
stdout
500500
500500
500500
4051657984
-243309312
1904174336