Find minimum number of Log value needed to calculate Log upto N in C++


As we know that log(x*y) = log(x) + log(y). So we will see what are the minimum number of log values are required to calculate all log values from 1 to N. So if N is 6, then output will be 3, as from log(1) to log(6), there are three log values are required except log(1). As log(1) is always 0, then ignore it, now for log(2) and log(3), we have to find. After that for log(4) this is log(2)+ log(2), but value of log(2) is known, so we do not calculate this again, for log(5), we need to calculate. So now count is 3, log(6) = log(3) + log(2), they are already known, so count is 3.

This problem can be reduced to find prime numbers in range 1 to N, as we can see that for prime numbers, we have to calculate the log values independently. Otherwise we have to factorize and calculate.

Example

 Live Demo

#include<iostream>
#include<vector>
#define MAX 1000005
using namespace std;
vector<int> prime(MAX, 1);
void seive(int N) {
   prime[0] = prime[1] = 0;
   for (int i = 2; i <= N; i++) {
      if (prime[i] == 1) {
         for (int j = 2; i * j <= N; j++)
         prime[i * j] = 0;
      }
   }
}
int numberOfLogs(int N) {
   int log_count = 0;
   seive(N);
   for (int i = 1; i <= N; i++) {
      if (prime[i] == 1)
      log_count++;
   }
   return log_count;
}
int main() {
   int N = 8;
   cout<<"Minimum number of log counts required: " << numberOfLogs(N)<<endl;
}

Output

Minimum number of log counts required: 4

Updated on: 18-Dec-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements