Friday, October 11, 2013

I need to calculate LCM of two numbers. There should be two classes written for it, PrimeFactor and LCM. I am badly stuck in its implementation. can someone help me please?

Here is code according to your requirement. it is running and easy to understand code. 

#include <iostream.h>

class PrimeFactor   //prime factor class
{
public:

       int number;
       int A[10];
       int B[10];
       int size;

       int* Prime_Factor()   //prime factor function
       {
              int PN[6]={2,3,5,7,11,13};
              int j=0, i=0;
             
              int x=number;
              while (x!=1)
              {
                     if ((x%PN[j])==0)
                     {
                           x=x/PN[j];
                           A[i]=PN[j];
                           i++;
                     }
                     else
                           j++;  
              }
              size=i;
              return A;
       }
};
class LCM:public PrimeFactor //LCM class inheriting PrimeFactor Class
{
public:
       int Calculate_LCM(LCM help)   //function to calculate LCM
       {
              int lcm=1;
              for (int i=0;i<this->size;i++)                  //For First Prime Factors Array
                     for (int j=0;j<help.size;j++)            //For Second Prime Factors Array
                     {if ((this->A[i])==(help.A[j]))  //Pairing
                                  if (this->A[i]!=0)
                                         {
                                                lcm=lcm*this->A[i];
                                                this->A[i]=0;
                                                help.A[j]=0;
                                 

                     }}
                     return lcm;
       }
};
void main()
{
       LCM P1, P2;
       int*k1;
       cout<<"\nEnter a number: ";
       cin>>P1.number;
       k1=P1.Prime_Factor();             //Prime Factors for First Number
       cout<<"The Factors of "<<P1.number<<" are:"<<endl;
       for (int i=0;i<P1.size;i++)
       {
                     cout<<*k1<<"  ";
                     k1++;
       }
       int*k2;
       cout<<"\nEnter a number: ";
       cin>>P2.number;
       k2=P2.Prime_Factor();             //Prime Factors for Second Number
       cout<<"The Factors of "<<P2.number<<" are:"<<endl;
       for (i=0;i<P2.size;i++)
       {
                     cout<<*k2<<"  ";
                     k2++;
       }
       int a;
       a=P1.Calculate_LCM(P2);
       cout<<endl<<"The LCM is "<<a<<endl;//Passing Prime Factors of First and Second Number to LCM Function


No comments:

Post a Comment