Prime Factors and their Powers
PROBLEM :
Given a number N, print all its unique prime factors and their powers in N.
N = 100
Factor Power
2 2
5 2
N = 35
Factor Power
5 1
7 1
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N.
Output:
Print all prime factors and their powers separated by spaces. The output should be printed in increasing order of prime factors.
Constraints:
1 = T = 200
2 = N = 10000
Example:
Input:
2
100
35
Output:
2 2 5 2
5 1 7 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
void Prime_Factors_Powers(int ) ;
void find_prime(int [],int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
Prime_Factors_Powers(no) ;
cout<<endl ;
}
return 0;
}
void Prime_Factors_Powers(int no)
{
int arr[no+1] ;
int i ;
find_prime(arr,no+1) ;
int curr,count ;
curr=arr[no] ;
count=1 ;
while(no>1)
{
no=no/curr ;
if(arr[no]==curr)
{
count++ ;
continue ;
}
cout<<curr<<" "<<count<<" " ;
curr=arr[no] ;
count=1 ;
}
}
void find_prime(int arr[],int no)
{
int i,j ;
arr[0]=0 ;
arr[1]=1 ;
j=2 ;
for(i=0;i<=no;i++)
arr[i]=i ;
for(i=2;i<=sqrt(no);i++)
{
if(arr[i]>=i)
{
for(j=i+i;j<=no;j+=i)
if(arr[j]>i)
arr[j]=i ;
}
}
}
---------------------------------------------------------------------------------
Given a number N, print all its unique prime factors and their powers in N.
N = 100
Factor Power
2 2
5 2
N = 35
Factor Power
5 1
7 1
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N.
Output:
Print all prime factors and their powers separated by spaces. The output should be printed in increasing order of prime factors.
Constraints:
1 = T = 200
2 = N = 10000
Example:
Input:
2
100
35
Output:
2 2 5 2
5 1 7 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
void Prime_Factors_Powers(int ) ;
void find_prime(int [],int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
Prime_Factors_Powers(no) ;
cout<<endl ;
}
return 0;
}
void Prime_Factors_Powers(int no)
{
int arr[no+1] ;
int i ;
find_prime(arr,no+1) ;
int curr,count ;
curr=arr[no] ;
count=1 ;
while(no>1)
{
no=no/curr ;
if(arr[no]==curr)
{
count++ ;
continue ;
}
cout<<curr<<" "<<count<<" " ;
curr=arr[no] ;
count=1 ;
}
}
void find_prime(int arr[],int no)
{
int i,j ;
arr[0]=0 ;
arr[1]=1 ;
j=2 ;
for(i=0;i<=no;i++)
arr[i]=i ;
for(i=2;i<=sqrt(no);i++)
{
if(arr[i]>=i)
{
for(j=i+i;j<=no;j+=i)
if(arr[j]>i)
arr[j]=i ;
}
}
}
---------------------------------------------------------------------------------
Comments
Post a Comment