Set and Unset bits

Lazy problem setter runs out of stories for this problem and doesn't want to gift arrays on birthdays. 

Construct a sequence of positive integers for which the greatest common divisor of their count of the set and unset bits is 1.

Find the nth element of the sequence

Example:

Input:  n = 5
Output: 6

Approach

C++

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

int setBits(int n)
{
    int res = 0;
    while (n)
    {
        res++;
        n = n & (n - 1);
    }
    return res;
}

vector<intv;
void initialize()
{

    for (int i = 1i <= 1000000i++)
    {
        int x = setBits(i);
        int y = log2(i) + 1 - x;
        int g = __gcd(xy);
        if (g == 1)
            v.push_back(i);
    }
    for (int i = 1000001;; i++)
    {
        int x = setBits(i);
        int y = log2(i) + 1 - x;
        int g = __gcd(xy);
        if (g == 1)
            v.push_back(i);
        if (v.size() >= 627509)
            break;
    }
}
int main()
{

    int n = 5;

    initialize();
    cout << v[n - 1] << "\n";
    return 0;
}


No comments:

Post a Comment