fork 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))
  13. * ((n + 1) >> (n & 1));
  14. }
  15.  
  16. int main() {
  17. // no overflow
  18. cout << sum_of_n<unsigned int>(1000) << endl;
  19. cout << sum_of_n<int>(1000) << endl;
  20. cout << sum_of_n_formula(1000) << endl;
  21. // overflow
  22. cout << sum_of_n<unsigned int>(1000000000) << endl;
  23. cout << sum_of_n<int>(1000000000) << endl;
  24. cout << sum_of_n_formula(1000000000) << endl;
  25. return 0;
  26. }
Success #stdin #stdout 1.01s 5668KB
stdin
Standard input is empty
stdout
500500
500500
500500
4051657984
-243309312
4051657984