Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void binary_search1() {
- long long sum = 10;
- long long l = 1,r = 100;
- while (l <= r) {
- long long m = (l + r) / 2;
- long long sum2 = m * (m + 1) / 2;
- if (sum2 == sum) {
- cout << m << '\n';
- return;
- } else if (sum2 > sum) {
- r = m - 1;
- } else {
- l = m + 1;
- }
- }
- }
- void binary_search2() {
- long long sum = 14;
- long long l = 1,r = 100;
- while (l <= r) {
- long long m = (l + r) / 2;
- long long sum2 = (m * (m + 1) * (2 * m + 1)) / 6;
- if (sum2 == sum) {
- cout << m << '\n';
- return;
- } else if (sum2 > sum) {
- r = m - 1;
- } else {
- l = m + 1;
- }
- }
- }
- void binary_search3 () {
- long long sum = 225;
- //~ 1^3 + 2^3 + 3^3 + 4^3 .....n^3
- long long s = 0;
- vector<long long> a;
- for (int i = 1; i <= 10; ++i) {
- s += pow(i,3);
- a.push_back(s);
- }
- int l = 0,r = (int) a.size();
- while (l <= r) {
- long long m = (l + r) / 2;
- if (a[m] == sum) {
- cout << m + 1 << '\n';
- return;
- } else if (a[m] > sum) {
- r = m - 1;
- } else {
- l = m + 1;
- }
- }
- }
- void binary_search4() {
- long long sum = 49;
- long long l = 1,r = 100;
- while (l <= r) {
- long long m = (l + r) / 2;
- long long sum2 = pow(m,2);
- if (sum2 == sum) {
- cout << m << '\n';
- return;
- } else if (sum2 > sum) {
- r = m - 1;
- } else {
- l = m + 1;
- }
- }
- }
- int main() {
- binary_search4();
- }
- //~ sum = 15;
- //~ 1...5 = 15
- //~ 1 + 2 + 3 + 4 + 5 + 6 = 21
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement