
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Number of Log Values Needed to Calculate Log Up to 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
#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