본문 바로가기
[Public] 수학/수치해석

[Hermeneutics] 1. 최대공약수와 최소공배수

by 차출발 2009. 9. 28.
반응형

수치해석(1)

2009. 09. 27()

 

 

*  최대공약수, 최소공배수를 구하는 툴을 만들어라

Ø  요구사항

-       두 수를 입력 가능하게 만들 것

-       두 수의 크기에 제한을 두지 않을 것

-       하나라도 1.0보다 작거나 정수가 아닌 경우에는 종료 할 것

-       함수를 이용할 것

 

Ø  Tip

-       최대공약수와 최소공배수의 곱은 두 수의 곱과 같다.

-       재귀 함수를 사용

-       재귀 호출의 횟수는 스택의 크기에 의해 제한을 받음

-       modf, fmod 함수 이용

 

#include <stdio.h>

#include <math.h>

 

#define ONESIZE 1001

#define RANGESIZE 1002

 

void InputData(double &A, double &B);

void OutputData(double A, double B);

void Error(int nError);

double GCD(double A, double B);

bool CheckingData(double A);

 

void main()

{

       double Value_A, Value_B;

       InputData(Value_A, Value_B);

       OutputData(Value_A, Value_B);

}

void InputData(double &A, double &B)

{

       printf("첫번째수입력하세요:");

       scanf("%lf", &A);

       printf("\n");

       printf("두번째수입력하세요:");

       scanf("%lf", &B);

       printf("\n");

}

void OutputData(double A, double B)

{

       printf("A = %lf,  B = %lf\n", A, B);

       if(!(CheckingData(A) || CheckingData(B)))

       {

             printf("최대공약수는= %lf\n", GCD(A, B));

             printf("최소공배수는= %lf\n", (A*B)/GCD(A, B));

       }

}

void Error(int nError)

{

       switch(nError)

       {

          case ONESIZE:

             printf("error : 적어도한수는1보다작습니다\n");

          break;

 

          case RANGESIZE:

             printf("error : 적어도한수는실수범위 입니다.\n");

          break;

 

          default:

          break;

       }

}

double GCD(double A, double B)

{

       if(A < B)

       {

             return GCD(B, A);

       }

       else if(fmod(A, B) == 0.0)

       {

             return B;

       }

       else

       {

             return GCD(B, fmod(A, B));

       }

}

 

bool CheckingData(double A)

{

       bool Result = false;

       double Buffer;

       if(A<1.0)

       {

             Error(ONESIZE);

             Result = true;

       }

       if( modf(A, &Buffer) != 0.0)

       {

             Error(RANGESIZE);

             Result = true;

       }

       return Result;

}