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;
primeFactors(n);
}
return 0;
}
Comments
Post a Comment