Question

How can I make a program that checks if binary representation of a given integer is periodical with period length m >= 2?

For example:

Binary representation of 10 is periodical

10 base 10 = 1010 base 2, periodical with period length 2

Binary representation of 9 is not periodical

9 base 10 = 1001 base 2

Binary representation of 153 is periodical

153 base 10 = 10011001 base 2, periodical with period length 4

Is there any specific algorithm for doing this?

I am working in C++.

Was it helpful?

Solution

What you can do is rotate the bits and check each time if the numbers are equal. i.e. the rotated one and the one you start with

// it is being assumed the size of int is 4bytes
int num = 153;
int temp = num;
int i = 0;
for (i=0; i<(8*sizeof(int))/2; i++){
    temp = ((temp >> 1) & LONG_MAX | temp << 31) // rotate the bits by 1
    if (!(temp ^ num)){ // check if the numbers are the same
        break;
    }
}
if (i<(8*sizeof(int))/2)
    std::cout << "Period is" << i << "\n";
else
    std::cout << "Not periodic";

The complexity is linear in the number of bits.

OTHER TIPS

KMP is the specific algorithm to find the period of any string, of source including the binary representation of a number, which is just a string. It run in O(n) time.

#include <iostream>
#include <algorithm>
using namespace std;

int calc_period(string s) {
  vector<int> pre(s.size());
  // this condition is keeped true in the for-loop:
  //    s[0..pre[i]] is this longest suffix of s[0..i] in s[0..i]'s all prefixes (if pre[i] >= 0)
  int k = -1;
  pre[0] = -1;
  for (int i = 1; i < int(s.size()); ++i) {
    while (k >= 0 && s[k + 1] != s[i]) {
      k = pre[k];
    }
    if (s[k + 1] == s[i]) {
      ++k;
    }
    pre[i] = k;
  }
  int l = s.size() - 1 - pre[s.size() - 1];
  return s.size() % l == 0 ? s.size() / l : 1;
}

string to_binary(long long x) {
  string s;
  if (x == 0) {
    s = "0";
  } else {
    while (x) {
      s += (x & 1) ? "1" : "0";
      x >>= 1;
    }
    reverse(s.begin(), s.end());
  }
  return s;
}

int main() {
  int x;
  cin >> x;
  cout << calc_period(to_binary(x)) << endl;
  return 0;
}

You can try this code out to see how it works. If you want to learn deeper about KMP, read its wiki page or related text books such as "Introduction to Algorithm".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top