程序八

来源:互联网 发布:电脑屏幕监控软件 编辑:程序博客网 时间:2024/04/29 09:05

题目:输入两个正整数m和n,求其最大公约数和最小公倍数.

1.程序分析:利用辗除法.

2.程序源代码:

 

#include <iostream>
#include <math.h>

using namespace std;

void getMaxDivisor( unsigned int numOne, unsigned int numTwo )
{
 if( numOne < 2 || numTwo < 2 )
  return ;

 unsigned int bufOne[1024] = {0};
 unsigned int bufTwo[1024] = {0};

 unsigned int idxOne = 0;
 unsigned int idxTwo = 0;

 unsigned int maxDivisor = 1;

 for( int i=2; i<=sqrt(numOne); i++ )
 {
  while( (numOne % i) == 0 )
  {
   numOne = numOne / i;
   bufOne[idxOne++] = i;
  }
 }
 
 if(numOne >= i)
     bufOne[idxOne++] = numOne;

 

 for( int j=2; j<=sqrt(numTwo); j++ )
 {
  while( (numTwo % j) == 0 )
  {
   numTwo = numTwo / j;
   bufTwo[idxTwo++] = j;
  }
 }
 
 if(numTwo >= j)
   bufTwo[idxTwo++] = numTwo;


 for( int k=0; k<idxOne; k++)
  cout<<bufOne[k]<<" ";
 cout<<endl;

 for( k=0; k<idxTwo; k++)
  cout<<bufTwo[k]<<" ";
 cout<<endl;


 for( i=0; i<idxOne; i++)
 {
  for( j=0; j<idxTwo; j++)
  {
   if( (bufOne[i] == bufTwo[j]) && (bufOne[i] != 0) )
   {
    maxDivisor *= bufOne[i];
    bufOne[i] = 0;
    bufTwo[j] = 0;
   }

  }
 }

 cout<<"The max Divisor is "<<maxDivisor<<endl;


}

void getMinMultiple( unsigned int numOne, unsigned int numTwo )
{
 if( numOne < 2 || numTwo < 2 )
  return;

 
 unsigned int bufOne[1024] = {0};
 unsigned int bufTwo[1024] = {0};
 
 unsigned int idxOne = 0;
 unsigned int idxTwo = 0;
 
 unsigned int maxDivisor = 1;
 
 for( int i=2; i<=sqrt(numOne); i++ )
 {
  while( (numOne % i) == 0 )
  {
   numOne = numOne / i;
   bufOne[idxOne++] = i;
  }
 }
 
 if(numOne >= i)
  bufOne[idxOne++] = numOne;
 
 
 
 for( int j=2; j<=sqrt(numTwo); j++ )
 {
  while( (numTwo % j) == 0 )
  {
   numTwo = numTwo / j;
   bufTwo[idxTwo++] = j;
  }
 }
 
 if(numTwo >= j)
  bufTwo[idxTwo++] = numTwo;
 
 
 for( int k=0; k<idxOne; k++)
  cout<<bufOne[k]<<" ";
 cout<<endl;
 
 for( k=0; k<idxTwo; k++)
  cout<<bufTwo[k]<<" ";
 cout<<endl;
 
 
 for( i=0; i<idxOne; i++)
 {
  for( j=0; j<idxTwo; j++)
  {
   if( (bufOne[i] == bufTwo[j]) && (bufOne[i] != 0) )
   {
    maxDivisor *= bufOne[i];
    bufOne[i] = 0;
    bufTwo[j] = 0;
   }
    
  }
 }

 for( i=0; i<idxOne; i++)
 {
  if(bufOne[i] != 0)
   maxDivisor *= bufOne[i];
 }

 for( j=0; j<idxTwo; j++)
  if(bufTwo[j] != 0)
   maxDivisor *= bufTwo[j];

 cout<<"The min Multiple is "<<maxDivisor<<endl;

 

}

void main()
{
 getMinMultiple( 12, 234 );

}

原创粉丝点击