Calculate factors of a number
displayFactors() displays all the factors of the given number. It takes the number as an input parameter and displays all the factors of the given number.
displayFactors() uses a function named factors() which takes 2 parameter:
first parameter is a pointer to the array for storing the factors for the given number and the second parameter is the number.
factors() returns the array of the calculated factors of the given number.
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
int*factors(int*arr,int num)
{
int noOfFactors=1;
int x=2;
if(num==0)
arr[noOfFactors++]=0;
else if(num==1)
arr[noOfFactors++]=1;
else if(num==2)
arr[noOfFactors++]=2;
else if(num==3)
arr[noOfFactors++]=3;
else
{
for(;num!=1;x++)
{
while(num%x==0)
{
num=num/x;
arr[noOfFactors++]=x;
}
}
}
arr[0]=noOfFactors-1;
return arr;
}
void displayFactors(int num)
{
int*new_arr;
new_arr=new int [20];
int*ptr=factors(new_arr,num);
int noOfFactors=ptr[0];
for(int i=1;i<=noOfFactors;i++)
cout<<ptr[i]<<" ";
cout<<endl;
delete new_arr;
}
int main()
{
cout<<"Factors of 0 are : "; displayFactors ( 0 ) ;
cout<<"Factors of 1 are : "; displayFactors ( 1 ) ;
cout<<"Factors of 2 are : "; displayFactors ( 2 ) ;
cout<<"Factors of 3 are : "; displayFactors ( 3 ) ;
cout<<"Factors of 4 are : "; displayFactors ( 4 ) ;
cout<<"Factors of 50 are : "; displayFactors ( 50 ) ;
cout<<"Factors of 99 are : "; displayFactors ( 99 ) ;
cout<<"Factors of 150 are : "; displayFactors ( 150 ) ;
cout<<"Factors of 999 are : "; displayFactors ( 999 ) ;
cout<<"Factors of 9999 are : "; displayFactors ( 9999 ) ;
_getche();
return 0;
}
Output
Factors of 0 are : 0
Factors of 1 are : 1
Factors of 2 are : 2
Factors of 3 are : 3
Factors of 4 are : 2 2
Factors of 50 are : 2 5 5
Factors of 99 are : 3 3 11
Factors of 150 are : 2 3 5 5
Factors of 999 are : 3 3 3 37
Factors of 9999 are : 3 3 11 101
0 comments:
Post a Comment