一行代碼實現1,2,3,,,n的和

Using the C++ language, have the function SimpleAdding(num) add up all the numbers from 1 to num. For example: if the input is 4 then your program should return 10 because 1 + 2 + 3 + 4 = 10. For the test cases, the parameter num will be any number from 1 to 1000.

solution:

#include <iostream>
using namespace std;

unsigned int SimpleAdding(unsigned int num) { 

  // code goes here   
  return num*(num+1)>>1; 

}

int main() { 

  // keep this function call here
  cout << SimpleAdding(gets(stdin));
  return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章