현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Python 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. # -*- encoding: ms949 -*-
  2. #  Filename: testCTime.py
  3. #  Execute: python testCTime.py
  4. from time import *
  5. # Python case
  6. weekNames = [ "월", "화", "수", "목", "금", "토", "일" ]  
  7. utctime = time()
  8. cNow = localtime(utctime)
  9. # 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  10. print("UTC: %d초" % int(utctime))
  11. # 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  12. print("%d년 %d월 %d일 (%s요일) %d시 %d분 %d초" % (cNow.tm_year, cNow.tm_mon, cNow.tm_mday, weekNames[cNow.tm_wday], cNow.tm_hour, cNow.tm_min, cNow.tm_sec) )
  13. # 1월 1일은 1, 1월 2일은 2
  14. # localtime().tz_isdat == 0 이면, 서머타임 없음
  15. # localtime().tz_isdat == 1 이면, 서머타임 있음
  16. if cNow.tm_isdst == 0:
  17.     strIsDST = "안함"
  18. else:
  19.     strIsDST = "함"
  20. print("올해 몇 번째 날: %d, 서머타임 적용 여부: %s" % (cNow.tm_yday, strIsDST))



실행> python testCTime.py
UTC: 1206324568
2008년 3월 24일 (월요일) 11시 9분 28초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함


실행> jython testCTime.py
UTC: 1206324572
2008년 3월 24일 (월요일) 11시 9분 32초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함



다음은 IronPython을 위해 새로 작성된 소스 코드이다.
인코딩에 ms949와 MS949는 에러가 생기고, cp949, CP949, euc-kr, EUC-KR 만 인식된다. 
날짜와 시간 관련 처리는 닷넷(C#)의 것을 따랐다.

  1. # -*- encoding: cp949 -*-
  2. #  Filename: testCTime.py
  3. #  Execute: ipy testCTime.py
  4. from System import *
  5. # Python/Jython/IronPython case
  6. weekNames = [ "월", "화", "수", "목", "금", "토", "일" ]  
  7. cNow = DateTime.Now
  8. StartOfEpoch = DateTime(1970, 1, 1)
  9. # 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  10. print "UTC: %d초" % (Convert.ToInt64((DateTime.UtcNow - StartOfEpoch).TotalMilliseconds)/1000L)
  11. # 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  12. print("%d년 %d월 %d일 (%s요일) %d시 %d분 %d초" % (cNow.Year, cNow.Month, cNow.Day, weekNames[int(cNow.DayOfWeek)], cNow.Hour, cNow.Minute, cNow.Second) )
  13. # cNow.IsDaylightSavingTime() == False 이면, 서머타임 없음
  14. # cNow.IsDaylightSavingTime() == True 이면, 서머타임 있음
  15. if cNow.IsDaylightSavingTime():
  16.     strIsDST = "함"
  17. else:
  18.     strIsDST = "안함"
  19. print("올해 몇 번째 날: %d , 서머타임 적용 여부: %s" % (cNow.DayOfYear, strIsDST))



실행> ipy testCTime.py
UTC: 1239235489초
2009년 4월 9일 (금요일) 9시 4분 49초
올해 몇 번째 날: 99 , 서머타임 적용 여부: 안함



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Groovy 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. /*
  2.  *  Filename: testCTime.groovy
  3.  *
  4.  *  Execute: groovy testCTime.groovy
  5.  */
  6. public class TestCTimeApp {
  7.    static def weekNames = [ "일", "월", "화", "수", "목", "금", "토" ].asImmutable()
  8.    public static void main(String[] args) {
  9.         Calendar now = new GregorianCalendar()
  10.         // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  11.         println("UTC: " + (now.getTime().getTime().intdiv(1000L)) + "초")
  12.         // 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  13.         print(now.get(Calendar.YEAR) + "년 ")
  14.         print((1 + now.get(Calendar.MONTH)) + "월 ")
  15.         print(now.get(Calendar.DAY_OF_MONTH) +"일 ")
  16.         print("(" + weekNames[now.get(Calendar.DAY_OF_WEEK)] + "요일) ")
  17.         print(now.get(Calendar.HOUR_OF_DAY) + "시 ")
  18.         print(now.get(Calendar.MINUTE) + "분 ")
  19.         println(now.get(Calendar.SECOND) + "초")
  20.         // 1월 1일은 1, 1월 2일은 2
  21.         print("올해 몇 번째 날: " + now.get(Calendar.DAY_OF_YEAR) +", ")
  22.         // 0 이면 서머타임 없음
  23.         println("서머타임 적용 여부: " + (now.get(Calendar.DST_OFFSET) == 0 ? "안함" : "함"))
  24.     }
  25. }



실행> groovy testCTime.groovy
UTC: 1206324111초
2008년 3월 24일 (화요일) 11시 1분 51초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Java 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. /*
  2.  *  Filename: TestCTimeApp.java
  3.  *
  4.  *  Compile: javac -d . TestCTimeApp.java
  5.  *
  6.  *  Execute: java TestCTimeApp
  7.  */
  8. import java.util.Calendar;
  9. import java.util.GregorianCalendar;
  10. public class TestCTimeApp {
  11.    static String[] weekNames = {
  12.                   "일", "월", "화", "수", "목", "금", "토"
  13.               };
  14.    public static void main(String[] args) {
  15.         Calendar now = new GregorianCalendar();
  16.         // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  17.         System.out.println("UTC: " + (now.getTime().getTime() / 1000L) + "초");
  18.         // 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  19.         System.out.print(now.get(Calendar.YEAR) + "년 ");
  20.         System.out.print((1 + now.get(Calendar.MONTH)) + "월 ");
  21.         System.out.print(now.get(Calendar.DAY_OF_MONTH) + "일 ");
  22.         System.out.print("(" + weekNames[now.get(Calendar.DAY_OF_WEEK)] + "요일) ");
  23.         System.out.print(now.get(Calendar.HOUR_OF_DAY) + "시 ");
  24.         System.out.print(now.get(Calendar.MINUTE) + "분 ");
  25.         System.out.println(now.get(Calendar.SECOND) + "초");
  26.         // 1월 1일은 1, 1월 2일은 2
  27.         System.out.print("올해 몇 번째 날: " + now.get(Calendar.DAY_OF_YEAR) + ", ");
  28.         // 0 이면 서머타임 없음
  29.         System.out.println("서머타임 적용 여부: " + (now.get(Calendar.DST_OFFSET) == 0 ? "안함" : "함"));
  30.     }
  31. }



컴파일> javac -d . TestCTimeApp.java

실행> java TestCTimeApp
UTC: 1206323913초
2008년 3월 24일 (화요일) 10시 58분 33초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 C++ 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. /*
  2.  *  Filename: testCTimeCPP.cpp
  3.  *
  4.  *  Compile: cl -GX testCTimeCPP.cpp
  5.  *
  6.  *  Execute: testCTimeCPP
  7.  */
  8. #include <iostream>
  9. #include <ctime>
  10. using namespace std;
  11. char weekNames[7][3] = {
  12.     "일", "월", "화", "수", "목", "금", "토"
  13. };
  14. int main() {
  15.     time_t timer;
  16.     struct tm *t;
  17.     timer = time(NULL); // 현재 시각을 초 단위로 얻기
  18.     t = localtime(&timer); // 초 단위의 시간을 분리하여 구조체에 넣기
  19.     // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  20.     cout << "UTC: " << timer << "초" << endl;
  21.     // 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  22.     cout << (t->tm_year + 1900) << "년 " << (t->tm_mon + 1) << "월 " << t->tm_mday << "일 (" << weekNames[t->tm_wday] << "요일) ";
  23.     cout << t->tm_hour << "시 " << t->tm_min << "분 " << t->tm_sec << "초" << endl;
  24.     // t->tm_yday의 값: 1월 1일은 0, 1월 2일은 1
  25.     cout << "올해 몇 번째 날: " << (1 + t->tm_yday);
  26.     // t->tm_isdst의 값: 0 이면 서머타임 없음
  27.     cout << "서머타임 적용 여부: " << ((t->tm_isdst == 0) ? "안함" : "함") << endl;
  28.     return 0;
  29. }



컴파일> cl testCTimeCPP.cpp

실행> testCTimeCPP
 UTC: 1206323262초
2008년 3월 24일 (월요일) 10시 47분 42초
올해 몇 번째 날: 84서머타임 적용 여부: 안함



Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 C 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)

  1. /*
  2.  *  Filename: testCTime.c
  3.  *
  4.  *  Compile: cl testCTime.c
  5.  *
  6.  *  Execute: testCTime
  7.  */
  8. #include <stdio.h>
  9. #include <time.h>
  10. char weekNames[7][3] = {
  11.  "일", "월", "화", "수", "목", "금", "토"
  12. };
  13. int main() {
  14.     time_t timer;
  15.     struct tm *t;
  16.     timer = time(NULL); // 현재 시각을 초 단위로 얻기
  17.     t = localtime(&timer); // 초 단위의 시간을 분리하여 구조체에 넣기
  18.     // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  19.     printf("UTC: %d초\n", timer);
  20.     // 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  21.     printf("%d년 %d월 %d일 (%s요일) ", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, weekNames[t->tm_wday]);
  22.     printf("%d시 %d분 %d초\n", t->tm_hour, t->tm_min, t->tm_sec);
  23.     // t->tm_yday의 값: 1월 1일은 0, 1월 2일은 1
  24.     printf("올해 몇 번째 날: %d, ", 1 + t->tm_yday);
  25.     // t->tm_isdst의 값: 0 이면 서머타임 없음
  26.     printf("서머타임 적용 여부: %s\n", (t->tm_isdst == 0) ? "안함" : "함");
  27.     return 0;
  28. }



컴파일> cl testCTime.c

실행> testCTime
UTC: 1206322402초
2008년 3월 24일 (월요일) 10시 33분 22초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함



Posted by Scripter
,

다음 소스 코드는 http://www.daniweb.com/code/snippet808.html 에서 볼 수 있는 (주어진 범위 안에서) 소수(prime number, 북한 용어로는 씨수) 찾기 C++ 소스 코드이다.
 

  1. # include<iostream.h>
  2. # include<math.h>
  3. void main()
  4. {
  5.     int flag=0;
  6.     unsigned long l, h, temp;
  7.     cout<<"Enter the lower limit:"; cin>>l;
  8.     cout<<"Enter the higher limit:"; cin>>h;
  9.     if(l%2==0)
  10.     {
  11.          if(l==2) cout<<"2\t";
  12.          l++; //taking only odd no
  13.     }
  14.      for(;l<=h;l+=2, flag=0)
  15.      {
  16.           temp=sqrt(l);
  17.           if(temp%2==0) temp++; //taking only odd no
  18.           for(; temp>2; temp--)
  19.          {
  20.              if(l%temp==0)
  21.              {
  22.                  flag=1;
  23.                  break;
  24.               }
  25.          }
  26.          if(flag==0) cout<<l<<"\t";
  27.     }
  28. }

우선 위의 코드를 파이썬 소스 코드 처럼 들여쓰기 규칙을 엄격히 적용하여 아래 처럼 재작성하였다.


  1. #include <iostream.h>
  2. # include <math.h>
  3. void main() {
  4.     int flag = 0;
  5.     unsigned long l, h, temp;
  6.     cout << "Enter the lower limit: ";
  7.     cin >> l;
  8.     cout << "Enter the upper limit: ";
  9.     cin >> h;
  10.     if (l % 2 == 0) {
  11.          if (l == 2)
  12.              cout << "2\t";
  13.          l++;    //  Taking only odd numbers.
  14.     }
  15.     for (; l <= h; l += 2, flag = 0) {
  16.         temp = sqrt(l);
  17.         if (temp % 2 == 0)
  18.            temp++;    //  Taking only odd numbers.
  19.         for (; temp > 2; temp--) {
  20.            if (l % temp == 0) {
  21.                flag = 1;
  22.                break;
  23.            }
  24.        }
  25.        if (flag == 0)
  26.            cout << l << "\t";
  27.     }
  28. }

하지만 아직 표준 C++에 맞지 않으므로 더 고쳐 보았다.

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. void main() {
  5.     int flag = 0;
  6.     unsigned long l, h, temp;
  7.     cout << "Enter the lower limit: ";
  8.     cin >> l;
  9.     cout << "Enter the upper limit: ";
  10.     cin >> h;
  11.     if (l % 2 == 0) {
  12.          if (l == 2)
  13.              cout << "2\t";
  14.          l++;    //  Taking only odd numbers.
  15.     }
  16.     for (; l <= h; l += 2, flag = 0) {
  17.         temp = sqrt(l);
  18.         if (temp % 2 == 0)
  19.            temp++;    //  Taking only odd numbers.
  20.         for (; temp > 2; temp--) {
  21.            if (l % temp == 0) {
  22.                flag = 1;
  23.                break;
  24.            }
  25.        }
  26.        if (flag == 0)
  27.            cout << l << "\t";
  28.     }
  29. }

이제 컴파일도 잘 되고 실행도 잘 될 것이다.
그러나 중요한 것은 알고리즘이다. 즉 소수인지 아닌지 확인하는 과정이 최적화되어 있느냐의 문제이다. 위의 소소 코드에서 27~32째 줄의 for 반복문 부분을 살펴보자,

            for (; temp > 2; temp--) {
               if (l % temp == 0) {
                   flag = 1;
                   break;
               }
          }

예를 들어 l =  3*1999993 = 5999979 인 경우 sqrt(5999979) ≒ 2449.5 이므로,
for 반복문을 시작하면서 temp = 2995 되고 t = 3 이 될 때 까지 무려 1496번을 반복하게 된다.
이 반복문 안의 나눗셈 과정  l % temp 부분을 l % 3 부터 시작하여 l % 5, l % 7, l % 9 ... 이런 식으로 증가시키면서 반복하는 과정으로 진행한다면, l =  3*1999993 = 5999979 인 경우 ㅣ% 3 = 0 이므로 더 이상 반복하지 않고 바로 반복문을 탈출하고 5999979는 소수가 아니라고 판정내린다.

이런 이유로 인하여, 위 소스 코드를 리팩토링하여 다음 처럼 수정하였다.


  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. void main() {
  5.     int flag = 0;
  6.     unsigned long l, h, j, temp;
  7.     cout << "Enter the lower limit: ";
  8.     cin >> l;
  9.     cout << "Enter the upper limit: ";
  10.     cin >> h;
  11.     if (l % 2 == 0) {
  12.          if (l == 2)
  13.              cout << "2\t";
  14.          l++;    //  Taking only odd numbers.
  15.     }
  16.     for (; l <= h; l += 2, flag = 0) {
  17.         temp = sqrt(l);
  18.         if (temp % 2 == 0)
  19.            temp++;    //  Taking only odd numbers.
  20.         for (j = 3L; j <= temp; j += 2L) {
  21.            if (l % j == 0L) {
  22.                flag = 1;
  23.                break;
  24.            }
  25.        }
  26.        if (flag == 0)
  27.            cout << l << "\t";
  28.     }
  29. }


 
컴파일> cl /GX findPrimes.cpp

실행> findPrimes
Enter the lower limit: 200
Enter the upper limit: 500
211     223     227     229     233     239     241     251     257     263
269     271     277     281     283     293     307     311     313     317
331     337     347     349     353     359     367     373     379     383
389     397     401     409     419     421     431     433     439     443
449     457     461     463     467     479     487     491     499



Creative Commons License


Posted by Scripter
,
GMP는 The GNU Multiple Precision Arithmetic Library(고정밀도 연산을 위한 GNU 라이브러리)의 줄임글로서 GNU MP라고도 한다. 리눅스 호환 환경이면 대부분 GMP는 이미 설치되어 있을 것이다. GMP의 공식 홈페이지는 http://gmplib.org 이고, GMP는 LGPL 하에서 배포된다.

또 gcc는 리눅스 호환 환경에서 쓸 수 있는 C 컴파일러(GNU C 컴파일러)이다. 대부분의 리눅스 호환 환경에는 gcc가  설치되어 있을 것이다.

다음 소스 코드는 GMP의 설치 테스트를 하기 위한 간단한 예제이다.

C 언어에서 GMP 라이브러리를 사용하기 위해서는 헤더 파일 gmp.h를 인클루드한다.
컴파일할 때는 반드시 컴파일 옵션 -lgmp 를 주어야 한다.
또 컴파일 옵션 -o testGMP 을 준 것은 생성될 실행파일명을 testGMP로 하라는 의미이다.
이 옵션을 생략하면 생성되는 실행파일명이 a.out(단, cygwin의 경우에는 a.exe)이다.

((  참고로, Visual C++ 6 에서 컴파일하는 명령은
           cl -I. testGMP.c /link gmp.lib /NODEFAULTLIB:LIBCMT
이다. 필자는 Visual C++ 6 에서 GMP 라이브러리를 사용하기 위해 영국에 사는 Brian Gladman 씨가 http://www.gladman.me.uk/computing/ 에서 제공하는 gmp-4.1.4.diffs.zip 을 써서 Visual C++ 6 용 GMP 라이브러리 gmp.lib 를 빌드하였다. ))

mpz_mul_ui 함수는 mpz_t 타입의 정수에 unsigned long 타입의 정수를 곱하는 함수이고,
mpz_add_ui 함수는 mpz_t 타입의 정수에 unsigned long 타입의 정수를 합하는 함수이다.

        mpz_init(r);

mpz_init 함수는 mpz_t 타입의 정수 변수를 초기화 하는 함수이다. (초기화된 값은 0)

       mpz_init_set_str(n, "123456", 10);

또 mpz_init_set_str 함수는 두번째 인수에 주어진 ASCIZ 문자열을 세 번째 인수에 주어진 적당한 진법(이 예에서는 10)을 적용하여 첫번째 인수에 주어진 mpz_t 타입의 정수 변수(이 예에서는 n)에 저장하는 함수이다.


  1. /*
  2.  *  Filename: testGMP.c
  3.  *
  4.  *   Compile: gcc -o testGMP testGMP.c -lgmp
  5.  *
  6.  *   Execute: ./testGMP
  7.  *    Output: 2470450
  8.  */
  9. #include <gmp.h>
  10. void foo(mpz_t result, const mpz_t param, unsigned long n) {
  11.     unsigned long i;
  12.     mpz_mul_ui(result, param, n);
  13.     for (i = 1; i < n; i++) {
  14.         mpz_add_ui (result, result, i*7);
  15.     }
  16. }
  17. int main(void) {
  18.     mpz_t r, n;
  19.     mpz_init(r);
  20.     mpz_init_set_str(n, "123456", 10);
  21.     foo(r, n, 20L);
  22.     gmp_printf("%Zd\n", r);
  23.     return 0;
  24. }



컴파일> gcc -o testGMP testGMP.c -lgmp

실행> ./testGMP
2470450



Win32의 Visual C++ 6 상에서 컴파일하기:
컴파일>cl -I. testGMP.c /link gmp.lib /NODEFAULTLIB:LIBCMT

실행> testGMP
2470450



Visual C++ 9.0 (Visual Studio 2008) 에서 컴파일하기:
컴파일>cl testGMP.c gmp.lib

실행> testGMP
2470450



Posted by Scripter
,
GMP는 The GNU Multiple Precision Arithmetic Library(고정밀도 연산을 위한 GNU 라이브러리)의 줄임글로서 GNU MP라고도 한다. 리눅스 호환 환경이면 대부분 GMP는 이미 설치되어 있을 것이다. GMP의 공식 홈페이지는 http://gmplib.org 이고, GMP는 LGPL 하에서 배포된다.

또 g++는 리눅스 호환 환경에서 쓸 수 있는 C++ 컴파일러(GNU C++ 컴파일러)이다. 대부분의 리눅스 호환 환경에는 g++도 역시 설치되어 있을 것이다.

다음 소스 코드는 GMP의 설치 테스트를 하기 위한 간단한 예제이다.

C 언어에서 GMP 라이브러리를 사용하기 위해서는 헤더 파일 gmp.h를 인클루드 하지만,
C++ 언어에서 GMP 라이브러리를 사용하기 위해서는 헤더 파일 gmpxx.h를 인클루드 한다.

헤더 파일 iostream.h 를 인클루드하고, 이름 공간 std를 사용한 것은 cout 구문을 쓰기 위함이다.
컴파일할 때는 반드시 컴파일 옵션 -lgmpxx -lgmp 을 주어야 한다. (순서도 중요함)
또 컴파일 옵션 -o testGMPXX 을 준 것은 생성될 실행파일명을 testGMPXX로 하라는 의미이다.
이 옵션을 생략하면 생성되는 실행파일명이 a.out(단, cygwin의 경우에는 a.exe)이다.

아래의 소스 코드 중에서

      b = "-5678";

부분은 b가 이미 mpz_class 타입으로 선언되어 있기 때문에 스트링이 mpz_class 타입으로 자동변환하게 된다. 즉, C 언어에서

     mpz_t  b;
     mpz_init_set_str(b, "-5678", 10);

라고 코딩한 것에 해당한다.


  1. /*
  2.  *  Filename:  testGMPXX.cc
  3.  *
  4.  *   Compile:  g++ -o testGMPXX testGMPXX.cc -lgmpxx -lgmp
  5.  *
  6.  *   Execute:  ./testGMPXX
  7.  */
  8. #include <gmpxx.h>
  9. #include <iostream>
  10. using namespace std;
  11. int main (void) {
  12.     mpz_class a, b, c;
  13.     a = 1234;
  14.     b = "-5678";
  15.     c = a + b;
  16.     cout << "sum is " << c << "\n";
  17.     cout << "absolute value is " << abs(c) << "\n";
  18.      return 0;
  19. }



컴파일> g++ -o testGMPXX testGMPXX.cc -lgmpxx -lgmp

실행> ./testGMPXX
sum is -4444
absolute value is 4444




* Visual C++ 9.0 (Visual Studio 2008) 에서 컴파일하기:
컴파일>cl testGMPXX.cpp gmp.lib

실행> testGMPXX
sum is -4444
absolute value is 4444



** 영문  위키피디아에서 소개하는 MinGW

** MinGW 의 공식 웹사이트에서 MinGW 를 설치하면 gcc 버전이 3.4.5 밖에 되지 않고,
    gmp 라이브러리도 수동으로 설치헤야 하는 번거로움이 있으므로,
    여기서는 Luna MinGW 를 설치하기로 한다. Luna MinGW 를 설치하면,
    현재 최신 버전인 gcc4.5.0 을 쓸 수 있다. 그 대신 g++ 로 컴파일 후에 쓰일 
    런타임 다이나믹 라이브러리 libgmpxx-4.dll 은 별도로 구하여 설치해야 한다.

** 윈도우에 Luna MinGW (with GCC 4.5.0) 설치하기:
      * Luna MinGW 홈페이지(MinGW GCC C/C++ Compiler package with installer) 
      * Luna MinGW 설치파일 다운로드
      1) 설치는 C:\MinGW 에 한것으로 간주한다.
      2) gcc 에서 gmp 라이브러리는 추가 설치 없이 바로 쓸 수 있는데,
         g++ 로는 컴파일은 되지만 컴파일된 실행파일을 실행하면 
         limgmpxx-4.dll 파일이 없다고 에러가 날 것이다. 이때는 아래 처럼 
         limgmpxx-4.dll 파일을 컴파일해서 만들던가 이미 만들어진 것을 PATH 가
         걸려 있는 곳에 넣어두어야 한다.
         아래는 limgmpxx-4.dll 파일을 구할 수 있는 곳이다. 
       
** g++에서 gmp를 사용하기 위해 libgmpxx-4.dll 구하여 설치하기:
      * 소스포지에서 libgmpxx-5.0.1-1-mingw32-dll-4.tar.lzma 다룬로드하기
      1)  확장명이 lzma 인 파일은 7zip 으로 풀어야 한다.
      2) 위의 파일을 받아서 7zip으로 압축 해제하여 libgmpxx-4.dll 을
          C:\MinGW\bin 에 복사힌다.
         (C:\MinGW 은 Luna MinGW 가 설치된 디렉토리이다)

** gcc 버전 확인하기
C:\test\mingw>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.5.0/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.5.0/configure --enable-languages=c,c++,ada,fortran,obj
c,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgo
mp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-r
untime-libs --disable-werror --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.5.0 (GCC)


** g++ 버전 확인하기
C:\test\mingw>g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.5.0/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.5.0/configure --enable-languages=c,c++,ada,fortran,obj
c,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgo
mp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-r
untime-libs --disable-werror --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.5.0 (GCC)


** Luna MinGW의 GCC 4.5.0 의 g++로 컴파일하기 (소스 파일의 확장명을 cc로 바꾸었다):
C:\test\mingw>g++ -o testGMPXX testGMPXX.cc -lgmpxx -lgmp

C:\test\mingw>testGMPXX
sum is -4444
absolute value is 4444




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
다항식 p(x) 를 1차 다항식 x - a 로 나눌 때의 몫과 나머지를 구하는 조립제법을
C++ 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

         p(x) = (x - a)q(x) + r

여기서 r은 나머지이며 r = p(a) 이다. 또 q(x)는 몫이다.

[참고]
    * 온라인으로 조립제법 표 만들기 손으로 계산하는 조립제법 표 
    * 온라인으로 구하는 다항식의 도함수: 조립제법을 이용한 다항식의 도함수



  1. /*
  2.  *  Filename: testSyntheticDivisionCPP.cpp
  3.  *
  4.  *  Purpose:  Find the quotient and remainder when some polynomial is
  5.  *            divided by a monic polynomial of the first degree.
  6.  *
  7.  *  Compile:  cl -GX testSyntheticDivisionCPP.cpp
  8.  *        Or  cl /EHsc testSyntheticDivisionCPP.cpp
  9.  *
  10.  *  Execute:  testSyntheticDivisionCPP -2 1 3 3 1
  11.  */
  12. #include <iostream>
  13. #include <string>
  14. #include <cmath>
  15. #include <memory>
  16. using namespace std;
  17. void print(char str[]) {
  18.     cout << str;
  19. }
  20. void println() {
  21.     cout << endl;
  22. }
  23. void println(char str[]) {
  24.     cout << str << endl;
  25. }
  26. // 사용법 표시
  27. void printUsage() {
  28.      cout << "사용법: testSyntheticDivisionCPP [수] [피제식의 계수들]" << endl;
  29.      cout << "조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다." << endl;
  30. }
  31. // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  32. char *simplify(double v) {
  33.     int n;
  34.     static char t[] = "                               ";
  35.     char tmp[] = "                               ";
  36.     sprintf(t, "%g", v);
  37.     n = strlen(t);
  38.     if ((n > 2) && (t[n - 2] == '.') && (t[n - 1] == '0'))
  39.         t[n-2] = '\0';
  40.     return (char *) t;
  41. }
  42. // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  43. // 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  44. char *simplify(double v, int width) {
  45.     int n, len;
  46.     static char t[] = "                               ";
  47.     char tmp[] = "                               ";
  48.     sprintf(t, "%g", v);
  49.     n = strlen(t);
  50.     if ((n > 2) && (t[n - 2] == '.') && (t[n - 1] == '0'))
  51.         t[n-2] = '\0';
  52.     len = strlen(t);
  53.     strcpy(tmp, t);
  54.     if (len < width) {
  55.         strncpy(t, "               ", width - len);
  56.         t[width - len] = '\0';
  57.         strcat(t, tmp);
  58.     }
  59.     return (char *) t;
  60. }
  61. // 다항식을 내림차순의 문자열로로 반환하는 함수
  62. // 반환된 문자열은 동적 메모리에 존재하므로.
  63. // 사용 후 반드시 해제(free)하여야 한다.
  64. char *toPolyString(double c[], int size) {
  65.     int SIZE = size;
  66.     int i;
  67.     static char t[300];
  68.     char tmp[80];
  69.     char *pc = simplify(c[0], -1);
  70.     char *pci;
  71.     if (SIZE > 2) {
  72.         if (strlen(pc) == 1 && pc[0] == '1')
  73.             sprintf(t,  "x^%d", SIZE - 1);
  74.         else if (strlen(pc) == 2 && pc[0] == '-' && pc[1] == '1')
  75.             sprintf(t,  "-x^%d", SIZE - 1);
  76.         else
  77.             sprintf(t,  "%s x^%d", simplify(c[0], -1), SIZE - 1);
  78.     }
  79.     else if (SIZE == 2) {
  80.         if (strlen(pc) == 1 && pc[0] == '1')
  81.             strcpy(t,  "x");
  82.         else if (strlen(pc) == 2 && pc[0] == '-' && pc[1] == '1')
  83.             strcpy(t,  "-x");
  84.         else
  85.             sprintf(t,  "%s x", simplify(c[0], -1));
  86.     }
  87.     else if (SIZE == 1) {
  88.         sprintf(t,  "%s", simplify(c[0], -1));
  89.     }
  90.     for (i = 1; i < SIZE; i++) {
  91.         pci = simplify(c[i], -1);
  92.         if (SIZE - 1 - i > 1) {
  93.             if (c[i] > 0.0) {
  94.                 if (strlen(pci) == 1 && pci[0] == '1') {
  95.                     sprintf(tmp,  " + x^%d", SIZE - 1 - i);
  96.                     strcat(t, tmp);
  97.                 }
  98.                 else {
  99.                     sprintf(tmp,  " + %s x^%d", simplify(c[i], -1), SIZE - 1 - i);
  100.                     strcat(t, tmp);
  101.                 }
  102.             }
  103.             else if (c[i] < 0.0) {
  104.                 if (strlen(pci) == 2 && pci[0] == '-' && pci[1] == '1') {
  105.                     sprintf(tmp,  " - x^%d", SIZE - 1 - i);
  106.                     strcat(t, tmp);
  107.                 }
  108.                 else {
  109.                     sprintf(tmp,  " - %s x^%d", simplify(fabs(c[i]), -1), SIZE - 1 - i);
  110.                     strcat(t, tmp);
  111.                 }
  112.             }
  113.         }
  114.         else if (SIZE - 1 - i == 1) {
  115.             if (c[i] > 0.0) {
  116.                 if (strlen(pci) == 1 && pci[0] == '1') {
  117.                     strcat(t, " + x");
  118.                 }
  119.                 else {
  120.                     sprintf(tmp,  " + %s x", simplify(c[i], -1));
  121.                     strcat(t, tmp);
  122.                 }
  123.             }
  124.             else if (c[i] < 0.0) {
  125.                 if (strlen(pci) == 2 && pci[0] == '-' && pci[1] == '1') {
  126.                     strcat(t, " - x");
  127.                 }
  128.                 else {
  129.                     sprintf(tmp,  " - %s x", simplify(fabs(c[i]), -1));
  130.                     strcat(t, tmp);
  131.                 }
  132.             }
  133.         }
  134.         else if (SIZE - 1 - i == 0) {
  135.             if (c[i] > 0.0) {
  136.                 sprintf(tmp,  " + %s", simplify(c[i], -1));
  137.                 strcat(t, tmp);
  138.             }
  139.             else if (c[i] < 0.0) {
  140.                 sprintf(tmp,  " - %s", simplify(fabs(c[i]), -1));
  141.                 strcat(t, tmp);
  142.             }
  143.         }
  144.     }
  145.     return (char *) t;
  146. }
  147. // 다항식 나눗셈 결과를
  148. //     (피제식) = (제식)(몫) + (나마지)
  149. // 형태로 출력
  150. void printDivisionResult(double a, double c[], double b[], int size) {
  151.     int SIZE = size;
  152.     int i;
  153.     double *pTmpPoly;
  154.     double r;
  155.     double monic[] = { 1.0, 0.0 };
  156.     print("  ");
  157.     print(toPolyString(c, SIZE));
  158.     println("");
  159.     print("    = ( ");
  160.     monic[1] = -a;
  161.     print(toPolyString(  monic, 2 ));
  162.     print(" )");
  163.     pTmpPoly = (double *)  calloc(SIZE - 1, sizeof(double));
  164.     for (i = 0; i < SIZE - 1; i++) {
  165.         pTmpPoly[i] = b[i];
  166.     }
  167.     print("( ");
  168.     print(toPolyString(pTmpPoly, SIZE - 1));
  169.     print(" )");
  170.     free(pTmpPoly);
  171.     r = b[SIZE - 1];
  172.     if (r > 0.0) {
  173.         print(" + ");
  174.         print(simplify(r, -1));
  175.     }
  176.     else if (r < 0.0) {
  177.         print(" - ");
  178.         print(simplify(fabs(r), -1));
  179.     }
  180.     println();
  181. }
  182. // 조립제법 계산표 출력 함수
  183. void printSyntheticTable(double a, double c[], double s[], double q[], int size) {
  184.     int SIZE = size;
  185.     int i;
  186.     print("       | ");
  187.     print(simplify(c[0], 6));
  188.     for (i = 1; i < SIZE; i++) {
  189.         print("  ");
  190.         print(simplify(c[i], 6));
  191.     }
  192.     println();
  193.     print(simplify(a, 6));
  194.     print(" | ");
  195.     print("        ");
  196.     print(simplify(s[1], 6));
  197.     for (i = 2; i < SIZE; i++) {
  198.         print("  ");
  199.         print(simplify(s[i], 6));
  200.     }
  201.     println();
  202.     print("       |-");
  203.     for (i = 0; i < SIZE; i++) {
  204.         print("--------");
  205.     }
  206.     println();
  207.     print("         ");
  208.     print(simplify(q[0], 6));
  209.     for (i = 1; i < SIZE; i++) {
  210.         print("  ");
  211.         print(simplify(q[i], 6));
  212.     }
  213.     println();
  214. }
  215. // C++ 언어의 실행 시작 지점
  216. int main(int argc, char *argv[]) {
  217.     int i;
  218.     int SIZE = argc - 2;
  219.     double a, c[15], s[15], b[15];
  220.     if (argc < 4) {
  221.         printUsage();
  222.         exit(1);
  223.     }
  224.     //////////////////////////////////////////////////////
  225.     // 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  226.     // 제식은 x -  a
  227.     a = atof(argv[1]);
  228.     for (i = 0; i < SIZE; i++) {
  229.      c[i] = atof(argv[i + 2]);
  230.     }
  231.     //////////////////////////////////////////////////////
  232.     // 조립제법의 주요 부분
  233.     s[0] = 0.0;
  234.     b[0] = c[0];
  235.     for (i = 1; i < SIZE; i++) {
  236.         s[i] = b[i-1]*a;
  237.         b[i] = c[i] + s[i];
  238.     }
  239.     print("몫의 계수는 ");
  240.     for (i = 0; i < SIZE - 2; i++) {
  241.         print(simplify(b[i], -1));
  242.         print(", ");
  243.     }
  244.     print(simplify(b[SIZE - 2], -1));
  245.     print(" 이고, 나머지는 ");
  246.     print(simplify(b[SIZE - 1], -1));
  247.     println(" 이다.");
  248.     println();
  249.     //////////////////////////////////////////////////////
  250.     // 조립제법 표를 출력한다.
  251.     printSyntheticTable(a, c, s, b, SIZE);
  252.     println();
  253.     //////////////////////////////////////////////////////
  254.     // (피제식) = (제식) x (몫) + (나머지)
  255.     printDivisionResult(a, c, b, SIZE);
  256.     return 0;
  257. }




컴파일> cl -EHsc testSyntheticDivisionCPP.cpp

실행> testSyntheticDivisionCPP 1 2 3 4 5
몫의 계수는 2, 5, 9 이고, 나머지는 14 이다.

       |      2       3       4       5
     1 |              2       5       9
       |---------------------------------
              2       5       9      14

  2 x^3 + 3 x^2 + 4 x + 5
    = ( x - 1 )( 2 x^2 + 5 x + 9 ) + 14



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,
다항식 p(x) 를 1차 다항식 x - a 로 나눌 때의 몫과 나머지를 구하는 조립제법을
C 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

         p(x) = (x - a)q(x) + r

여기서 r은 나머지이며 r = p(a) 이다. 또 q(x)는 몫이다.

[참고]
    * 온라인으로 조립제법 표 만들기 손으로 계산하는 조립제법 표 
    * 온라인으로 구하는 다항식의 도함수: 조립제법을 이용한 다항식의 도함수


아래의 소스파일은 Ch를 사용하면 컴파일하지 않고 수정 없이 그대로 실행된다.
(실행 예:  ch testSyntheticDivision.c 1 2 3 4 5  )


  1. /*
  2.  *  Filename: testSyntheticDivision.c
  3.  *
  4.  *  Purpose:  Find the quotient and remainder when some polynomial is
  5.  *            divided by a monic polynomial of the first degree.
  6.  *
  7.  *  Compile:  cl testSyntheticDivision.c
  8.  *
  9.  *  Execute:  testSyntheticDivision -2 1 3 3 1
  10.  */
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <math.h>
  14. #include <memory.h>
  15. void print(char str[]) {
  16.     printf("%s", str);
  17. }
  18. void println(char str[]) {
  19.     printf("%s\n", str);
  20. }
  21. // 사용법 표시
  22. void printUsage() {
  23.      println("사용법: testSyntheticDivision [수] [피제식의 계수들]");
  24.      println("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.");
  25. }
  26. // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  27. // 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  28. char *simplify(double v, int width) {
  29.     int n, len;
  30.     static char t[] = "                               ";
  31.     char tmp[] = "                               ";
  32.     sprintf(t, "%g", v);
  33.     n = strlen(t);
  34.     if ((n > 2) && (t[n - 2] == '.') && (t[n - 1] == '0'))
  35.         t[n-2] = '\0';
  36.     len = strlen(t);
  37.     strcpy(tmp, t);
  38.     if (len < width) {
  39.         strncpy(t, "               ", width - len);
  40.         t[width - len] = '\0';
  41.         strcat(t, tmp);
  42.     }
  43.     return (char *) t;
  44. }
  45. // 다항식을 내림차순의 문자열로로 반환하는 함수
  46. // 반환된 문자열은 동적 메모리에 존재하므로.
  47. // 사용 후 반드시 해제(free)하여야 한다.
  48. char *toPolyString(double c[], int size) {
  49.     int SIZE = size;
  50.     int i;
  51.     static char t[300];
  52.     char tmp[80];
  53.     char *pc = simplify(c[0], -1);
  54.     char *pci;
  55.     if (SIZE > 2) {
  56.         if (strlen(pc) == 1 && pc[0] == '1')
  57.             sprintf(t,  "x^%d", SIZE - 1);
  58.         else if (strlen(pc) == 2 && pc[0] == '-' && pc[1] == '1')
  59.             sprintf(t,  "-x^%d", SIZE - 1);
  60.         else
  61.             sprintf(t,  "%s x^%d", simplify(c[0], -1), SIZE - 1);
  62.     }
  63.     else if (SIZE == 2) {
  64.         if (strlen(pc) == 1 && pc[0] == '1')
  65.             strcpy(t,  "x");
  66.         else if (strlen(pc) == 2 && pc[0] == '-' && pc[1] == '1')
  67.             strcpy(t,  "-x");
  68.         else
  69.             sprintf(t,  "%s x", simplify(c[0], -1));
  70.     }
  71.     else if (SIZE == 1) {
  72.         sprintf(t,  "%s", simplify(c[0], -1));
  73.     }
  74.     for (i = 1; i < SIZE; i++) {
  75.         pci = simplify(c[i], -1);
  76.         if (SIZE - 1 - i > 1) {
  77.             if (c[i] > 0.0) {
  78.                 if (strlen(pci) == 1 && pci[0] == '1') {
  79.                     sprintf(tmp,  " + x^%d", SIZE - 1 - i);
  80.                     strcat(t, tmp);
  81.                 }
  82.                 else {
  83.                     sprintf(tmp,  " + %s x^%d", simplify(c[i], -1), SIZE - 1 - i);
  84.                     strcat(t, tmp);
  85.                 }
  86.             }
  87.             else if (c[i] < 0.0) {
  88.                 if (strlen(pci) == 2 && pci[0] == '-' && pci[1] == '1') {
  89.                     sprintf(tmp,  " - x^%d", SIZE - 1 - i);
  90.                     strcat(t, tmp);
  91.                 }
  92.                 else {
  93.                     sprintf(tmp,  " - %s x^%d", simplify(fabs(c[i]), -1), SIZE - 1 - i);
  94.                     strcat(t, tmp);
  95.                 }
  96.             }
  97.         }
  98.         else if (SIZE - 1 - i == 1) {
  99.             if (c[i] > 0.0) {
  100.                 if (strlen(pci) == 1 && pci[0] == '1') {
  101.                     strcat(t, " + x");
  102.                 }
  103.                 else {
  104.                     sprintf(tmp,  " + %s x", simplify(c[i], -1));
  105.                     strcat(t, tmp);
  106.                 }
  107.             }
  108.             else if (c[i] < 0.0) {
  109.                 if (strlen(pci) == 2 && pci[0] == '-' && pci[1] == '1') {
  110.                     strcat(t, " - x");
  111.                 }
  112.                 else {
  113.                     sprintf(tmp,  " - %s x", simplify(fabs(c[i]), -1));
  114.                     strcat(t, tmp);
  115.                 }
  116.             }
  117.         }
  118.         else if (SIZE - 1 - i == 0) {
  119.             if (c[i] > 0.0) {
  120.                 sprintf(tmp,  " + %s", simplify(c[i], -1));
  121.                 strcat(t, tmp);
  122.             }
  123.             else if (c[i] < 0.0) {
  124.                 sprintf(tmp,  " - %s", simplify(fabs(c[i]), -1));
  125.                 strcat(t, tmp);
  126.             }
  127.         }
  128.     }
  129.     return (char *) t;
  130. }
  131. // 다향식 나눗셈 결과를
  132. //     (피제식) = (제식)(몫) + (나마지)
  133. // 형태로 출력
  134. void printDivisionResult(double a, double c[], double b[], int size) {
  135.     int SIZE = size;
  136.     int i;
  137.     double *pTmpPoly;
  138.     double r;
  139.     double monic[] = { 1.0, 0.0 };
  140.     print("  ");
  141.     print(toPolyString(c, SIZE));
  142.     println("");
  143.     print("    = ( ");
  144.     monic[1] = -a;
  145.     print(toPolyString(  monic, 2 ));
  146.     print(" )");
  147.     pTmpPoly = (double *)  calloc(SIZE - 1, sizeof(double));
  148.     for (i = 0; i < SIZE - 1; i++) {
  149.         pTmpPoly[i] = b[i];
  150.     }
  151.     print("( ");
  152.     print(toPolyString(pTmpPoly, SIZE - 1));
  153.     print(" )");
  154.     free(pTmpPoly);
  155.     r = b[SIZE - 1];
  156.     if (r > 0.0) {
  157.         print(" + ");
  158.         print(simplify(r, -1));
  159.     }
  160.     else if (r < 0.0) {
  161.         print(" - ");
  162.         print(simplify(fabs(r), -1));
  163.     }
  164.     println("");
  165. }
  166. // 조립제법 계산표 출력 함수
  167. void printSyntheticTable(double a, double c[], double s[], double q[], int size) {
  168.     int SIZE = size;
  169.     int i;
  170.     print("       | ");
  171.     print(simplify(c[0], 6));
  172.     for (i = 1; i < SIZE; i++) {
  173.         print("  ");
  174.         print(simplify(c[i], 6));
  175.     }
  176.     println("");
  177.     print(simplify(a, 6));
  178.     print(" | ");
  179.     print("        ");
  180.     print(simplify(s[1], 6));
  181.     for (i = 2; i < SIZE; i++) {
  182.         print("  ");
  183.         print(simplify(s[i], 6));
  184.     }
  185.     println("");
  186.     print("       |-");
  187.     for (i = 0; i < SIZE; i++) {
  188.         print("--------");
  189.     }
  190.     println("");
  191.     print("         ");
  192.     print(simplify(q[0], 6));
  193.     for (i = 1; i < SIZE; i++) {
  194.         print("  ");
  195.         print(simplify(q[i], 6));
  196.     }
  197.     println("");
  198. }
  199. // C/C++/Ch 언어의 실행 시작 지점
  200. int main(int argc, char *argv[]) {
  201.     int i;
  202.     int SIZE = argc - 2;
  203.     double a, c[15], s[15], b[15];
  204.     if (argc < 4) {
  205.         printUsage();
  206.         exit(1);
  207.     }
  208.     //////////////////////////////////////////////////////
  209.     // 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  210.     // 제식은 x -  a
  211.     a = atof(argv[1]);
  212.     for (i = 0; i < SIZE; i++) {
  213.         c[i] = atof(argv[i + 2]);
  214.     }
  215.     //////////////////////////////////////////////////////
  216.     // 조립제법의 주요 부분
  217.     s[0] = 0.0;
  218.     b[0] = c[0];
  219.     for (i = 1; i < SIZE; i++) {
  220.         s[i] = b[i-1]*a;
  221.         b[i] = c[i] + s[i];
  222.     }
  223.     //////////////////////////////////////////////////////
  224.     // 몫의 계수와 나머지를 출력한다.
  225.     print("몫의 계수는 ");
  226.     for (i = 0; i < SIZE - 2; i++) {
  227.         print(simplify(b[i], -1));
  228.         print(", ");
  229.     }
  230.     print(simplify(b[SIZE - 2], -1));
  231.     print(" 이고, 나머지는 ");
  232.     print(simplify(b[SIZE - 1], -1));
  233.     println(" 이다.");
  234.     println("");
  235.     //////////////////////////////////////////////////////
  236.     // 조립제법 표를 출력한다.
  237.     printSyntheticTable(a, c, s, b, SIZE);
  238.     println("");
  239.     //////////////////////////////////////////////////////
  240.     // (피제식) = (제식) x (몫) + (나머지)
  241.     printDivisionResult(a, c, b, SIZE);
  242.     return 0;
  243. }




컴파일> cl testSyntheticDivision.c

실행> testSyntheticDivision 1 2 3 4 5
몫의 계수는 2, 5, 9 이고, 나머지는 14 이다.

       |      2       3       4       5
     1 |              2       5       9
       |---------------------------------
              2       5       9      14

  2 x^3 + 3 x^2 + 4 x + 5
    = ( x - 1 )( 2 x^2 + 5 x + 9 ) + 14



 

Posted by Scripter
,