Advertisement
newb_ie

bs

Aug 26th, 2021
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. void binary_search1() {
  2. long long sum = 10;
  3. long long l = 1,r = 100;
  4. while (l <= r) {
  5. long long m = (l + r) / 2;
  6. long long sum2 = m * (m + 1) / 2;
  7. if (sum2 == sum) {
  8. cout << m << '\n';
  9. return;
  10. } else if (sum2 > sum) {
  11. r = m - 1;
  12. } else {
  13. l = m + 1;
  14. }
  15. }
  16. }
  17. void binary_search2() {
  18. long long sum = 14;
  19. long long l = 1,r = 100;
  20. while (l <= r) {
  21. long long m = (l + r) / 2;
  22. long long sum2 = (m * (m + 1) * (2 * m + 1)) / 6;
  23. if (sum2 == sum) {
  24. cout << m << '\n';
  25. return;
  26. } else if (sum2 > sum) {
  27. r = m - 1;
  28. } else {
  29. l = m + 1;
  30. }
  31. }
  32. }
  33. void binary_search3 () {
  34. long long sum = 225;
  35. //~ 1^3 + 2^3 + 3^3 + 4^3 .....n^3
  36. long long s = 0;
  37. vector<long long> a;
  38. for (int i = 1; i <= 10; ++i) {
  39. s += pow(i,3);
  40. a.push_back(s);
  41. }
  42. int l = 0,r = (int) a.size();
  43. while (l <= r) {
  44. long long m = (l + r) / 2;
  45. if (a[m] == sum) {
  46. cout << m + 1 << '\n';
  47. return;
  48. } else if (a[m] > sum) {
  49. r = m - 1;
  50. } else {
  51. l = m + 1;
  52. }
  53. }
  54. }
  55.  
  56. void binary_search4() {
  57. long long sum = 49;
  58. long long l = 1,r = 100;
  59. while (l <= r) {
  60. long long m = (l + r) / 2;
  61. long long sum2 = pow(m,2);
  62. if (sum2 == sum) {
  63. cout << m << '\n';
  64. return;
  65. } else if (sum2 > sum) {
  66. r = m - 1;
  67. } else {
  68. l = m + 1;
  69. }
  70. }
  71. }
  72.  
  73. int main() {
  74. binary_search4();
  75. }
  76.  
  77.  
  78. //~ sum = 15;
  79. //~ 1...5 = 15
  80.  
  81. //~ 1 + 2 + 3 + 4 + 5 + 6 = 21
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement