본문 바로가기
IT/C Language

소수의 합 구하기

by Jang HyunWoong 2014. 12. 19.

알고리즘 중

---------------------------------------------------

10 이하의 소수를 모두 더하면 2+2+5+7 = 17이 됩니다. 

 

이백만(2,000,000) 이하 소수의 합은 얼마입니까?

---------------------------------------------------

 

간단하게 C++ 로 구현해봤다. 

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int sosoo(int x);
  5.  
  6. int main() {
  7. // your code goes here
  8. int result = 0;
  9.  
  10. for(int i=1; i<=30; i++)
  11. {
  12. result += sosoo(i);
  13. }
  14.  
  15. cout << "결과 = " << result << endl;
  16.  
  17. return 0;
  18. }
  19.  
  20. int sosoo(int x)
  21. {
  22. int count = 0;
  23.  
  24. for(int j=1; j<=x; j++)
  25. {
  26. if(x%j == 0)
  27. {
  28. count++;
  29. }
  30. }
  31. if(count == 2)
  32. return x;
  33. else
  34. return 0;
  35. }

 

온라인으로 소스를 돌리기 때문에 숫자를 2백만까지 못했다. 

30으로 테스트했다.

결과 = 129

 

반응형