haribhatt34's blog

By haribhatt34, history, 5 years ago, In English

Link to the problem

Link to my solution

My Solution -

#include <bits/stdc++.h>
using namespace std;

map<int, int> mp;

int findPower(int i, int k)
{
    int t = i, cnt = 0;
    while (t <= k)
    {
	if (mp.find(t) != mp.end())
	{
	    cnt += mp[t];
	    break;
	}
	t *= 2;
	++cnt;
    }
    return mp[i] = cnt;
}

int main()
{
    int n, k;
    cin >> n >> k;
    // power of 2
    vector<int> p2(31);
    p2[0] = 1;
    for (int i=1; i<p2.size(); ++i)	p2[i] = p2[i-1] * 2;

    long double b = 0.0;
    for (int i=n; i>=1; --i)
    {
	int p = findPower(i, k);
	p = p2[p];
	b += (long double)1/p;
    }
    cout << ((long double)1/n) * b << '\n';
    return 0;
}

I know my solution is unnecessarily long, I was trying to catch value, so to use them later. I don't know what I am doing wrong, moreover I am not getting correct decimal precision. For sample — 100000 5, the output should be — 0.999973749998, but my program is returning 0.9999687500, why could it be?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it +3 Vote: I do not like it

u can use cout << fixed ; cout << setprecision(15) i did same and get ac

»
5 years ago, # |
  Vote: I like it +5 Vote: I do not like it

Change while (t <= k) to while (t < k).