//this program:
//factors a given number
#include <iostream>
#include <cmath>
#include "Declarations.h"
usingnamespace std;
int fact_number;
int main()
{
int n; //holds the number to factor
Factor factor; //Factor object
//get a number from the user
cout<<"Enter a number. ";
cin>>n;
factor.set_num(n); //factor the number
//print the factors
cout<<"The factors for "<<n<<" are:\n\n";
cout<<factor.results(fact_number);
//terminate program
return 0;
}
//------------------------------------------------------------------------------
//Factor class functions
void Factor::fact() //factors 'num', stores factors in 'factors'
{
int i; //loop variable
int prime_num=2; //holds prime numbers
//factor
for(i=0; i<MAX_FACTORS && num>prime_num;)
{
if(num%prime_num==0) //this means 'prime_num' is a factor
{
factors[i]=prime_num; //store the factor
i++;
num/=prime_num; //divide 'num' by its factor
}
else
{
while(!prime(prime_num)) //make 'prime_num' prime
{
prime_num++;
}
}
}
fact_number=i;
}
bool Factor::prime(int n) //returns true if prime
{
int i; //loop variable
for(i=2; i<=sqrt(n); i++)
{
if(n%i==0) //if not prime
{
returnfalse;
}
}
returntrue;
}
void Factor::results(int a) //prints the factors
{
//'a' is how many elements of 'factors' were initialized
for(int i=0; i<a; i++)
{
cout<<factors[i]<<endl;
}
}
//-----------------------------------------------------------------------------
Declarations.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#define MAX_FACTORS 50 //maxium number of factors
//factors a given number
class Factor
{
private:
int num; //holds the number to factor
int factors[MAX_FACTORS]; //holds the factors of a number 'num'
public:
void set_num(int a) //sets 'num'
{num=a; fact();}
void results(int a); //prints the factors
private:
void fact(); //factors 'num', stores factors in 'factors'
bool prime(int n); //returns true if prime
};