Posts

Showing posts with the label Prime numbers

Prime factors and their powers using maps

/* N = 100 Factor Power   2      2   5      2 N = 35 Factor  Power   5      1   7      1     nput: 2 100 35 Output: 2 2 5 2 5 1 7 1 we can see it as key value printing we can use map */ #include <bits/stdc++.h> using namespace std; void primeFactors(int n) { map<int,int> m; while(n%2==0) // runs two times for 100 making it 25, covered divisible by 4 { m[2]++; n=n/2; } for(int i=3;i<=n;i=i+2) // checking for all odd numbers note if 3 checked then it wont check for 9 only primes { while(n%i==0) { m[i]++; n=n/i; } } map<int,int> ::iterator itr; for(itr=m.begin();itr!=m.end();itr++) { cout<<itr->first<<" "<<itr->second<<" "; } cout<<endl; } int main() { int n,i,t; cin >> t; while(t--){     cin >> n; ...
// sieve of Atkin is a popular way to find all the prime numbers in range using the dp approach and is //better than the erronthesis approach // C++ program for implementation of Sieve of Atkin #include <bits/stdc++.h> using namespace std;   int SieveOfAtkin(int limit) {     // 2 and 3 are known to be prime     if (limit > 2)         cout << 2 << " ";     if (limit > 3)         cout << 3 << " ";       // Initialise the sieve array with false values     bool sieve[limit];     for (int i = 0; i < limit; i++)         sieve[i] = false;     for (int x = 1; x * x < limit; x++) {         for (int y = 1; y * y < limit; y++) {                           // Main part of Sieve of Atkin       ...

Composites and Primes Sieve of Eratosthenes dp

/* Given two integers L and R find the difference of number of composites and primes between the range L and R (both inclusive). Input: First line of input contains of an integer 'T' denoting number of test cases . Then T test cases follow. Each test contains two integers L and R . Output: For each case print an integer corresponding to the answer . Constraints: 1<=T<=100 1<=L<=R<=10^7 Example: Input: 2 4 4 4 6 Output: 1 1 */ // given l , r print no of comp- no of prime  T.C->0.21 // normal approac i*i<=n gives TLE > 3.14 #include<bits/stdc++.h> using namespace std; bool prime[100001]; void SieveOfEratosthenes() {     memset(prime, true, sizeof(prime));     prime[0]=false;     prime[1]=false;     for (int p=2; p*p<=10000000; p++)     {             if (prime[p] == true) // we make all multiples of prime false       ...
Hello guys.. Here you can find all the important programming questions that i have solved.., if you get any doubt feel free to ask below in comment section :)