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

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

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

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


아래의 소스파일은 Ruby용 소스파일 testSyntheticDivision.rb 를 Lua용으로 수정한 것이다.


  1. --[[
  2.   Filename: testSyntheticDivision.lua
  3.   Purpose:  Find the quotient and remainder when some polynomial is
  4.             divided by a monic polynomial of the first degree.
  5.   Execute:  lua testSyntheticDivision.lua -2 1 3 3 1
  6. --]]
  7. -- 사용법 표시
  8. function printUsage()
  9.     print("사용법: lua testSyntheticDivision.lua [수] [피제식의 계수들]")
  10.     print("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.")
  11. end   
  12. -- 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  13. -- 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  14. function simplify(v, width)
  15.     t = "" .. v
  16.     tlen = string.len(t)
  17.     if string.sub(t, tlen-2) == ".0" then
  18.         t = string.sub(t, 0, tlen-2)
  19.     end
  20.     if width ~= nil then
  21.         if tlen < width then
  22.             t = string.sub("              ", 0, width - tlen) .. t
  23.         end
  24.     end
  25.     return t
  26. end
  27. -- 다항식을 내림차순의 스트링 표현으로 반환
  28. function toPolyString(c)
  29.     local t = ""
  30.     sc0 = simplify(c[1], null)
  31.     if #c > 2 then
  32.         if sc0 == "1" then
  33.             t = t .. "x^" .. (#c-1)
  34.         elseif sc0 == "-1" then
  35.             t = t .. "-x^" .. (#c-1)
  36.         else
  37.             t = t .. sc0 .. " x^" .. (#c-1)
  38.         end
  39.     elseif #c == 2 then
  40.         if sc0 == "1" then
  41.             t = t .. "x"
  42.         elseif sc0 == "-1" then
  43.             t = t .. "-x"
  44.         else
  45.             t = t .. sc0 .. " x"
  46.         end
  47.     elseif #c == 1 then
  48.         t = t .. sc0
  49.     end
  50.     for i = 2, #c do
  51.         k = #c - i
  52.         sc = simplify(c[i], nil)
  53.         if k > 1 then
  54.             if c[i] > 0.0 then
  55.                 if sc == "1" then
  56.                     t = t .. " + " .. "x^" .. k
  57.                 else
  58.                     t = t .. " + " .. sc .. " x^" .. k
  59.                 end
  60.             elseif c[i] < 0.0 then
  61.                 if sc == "-1" then
  62.                     t = t .. " - " .. "x^" .. k
  63.                 else
  64.                     t = t .. " - " .. simplify(math.abs(c[i]), nil) .. " x^" .. k
  65.                 end
  66.             end
  67.         elseif k == 1 then
  68.             if c[i] > 0.0 then
  69.                 if sc == "1" then
  70.                     t = t .. " + " .. "x"
  71.                 else
  72.                     t = t .. " + " .. sc .. " x"
  73.                 end
  74.             elseif c[i] < 0.0 then
  75.                 if sc == "-1" then
  76.                     t = t .. " - " .. "x"
  77.                 else
  78.                     t = t .. " - " .. simplify(math.abs(c[i]), null) .. " x"
  79.                 end
  80.             end
  81.         elseif k == 0 then
  82.             if c[i] > 0.0 then
  83.                 t = t .. " + " .. sc
  84.             elseif c[i] < 0.0 then
  85.                 t = t .. " - " .. simplify(math.abs(c[i]), null)
  86.             end
  87.         end
  88.     end
  89.     return t
  90. end
  91. -- 다향식 나눗셈 결과를
  92. --     (피제식) = (제식)(몫) + (나마지)
  93. -- 형태로 출력
  94. function printDivisionResult(a, c, b)
  95.     local strLine = "  " .. toPolyString(c)
  96.     io.write( strLine .. "\n")
  97.     strLine = "    = ( " .. toPolyString( { 1.0, -a } ) .. " )"
  98.     tmp = { }
  99.     for i = 1, #b - 1 do
  100.         tmp[i] = b[i]
  101.     end
  102.     strLine = strLine .. "( " .. toPolyString(tmp) .. " )"
  103.     r = b[#b]
  104.     if r > 0.0 then
  105.         strLine = strLine .. " + " .. simplify(r, nil)
  106.     elseif r < 0.0 then
  107.         strLine = strLine .. " - " .. simplify(math.abs(r), nil)
  108.     end
  109.     io.write( strLine .. "\n" )
  110. end
  111. -- 조립제법 계산표 출력 함수
  112. function printSyntheticTable(a, c, s, q)
  113.     strLine = "       | "
  114.     strLine = strLine .. simplify(c[1], 6)
  115.     for i = 2, #c do
  116.         strLine = strLine .. "  " .. simplify(c[i], 6)
  117.     end
  118.     io.write( strLine .. "\n" )
  119.     strLine = simplify(a, 6) ..  " |"
  120.     strLine = strLine .. "         "
  121.     strLine = strLine .. simplify(s[2], 6)
  122.     for i = 3, #s do
  123.         strLine = strLine .. "  " .. simplify(s[i], 6)
  124.     end
  125.     io.write( strLine .. "\n" )
  126.     strLine = "       |"
  127.     for i = 1, #q do
  128.         strLine = strLine .. "--------"
  129.     end
  130.     io.write( strLine .. "\n" )
  131.     strLine = "         "
  132.     strLine = strLine .. simplify(q[1], 6)
  133.     for i = 2, #q do
  134.         strLine = strLine .. "  " .. simplify(q[i], 6)
  135.     end
  136.     io.write( strLine .. "\n" )
  137. end
  138. -- 실행 시작 지점
  139. if #arg < 3 then
  140.     printUsage()
  141.     os.exit(1)
  142. end
  143. -- 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  144. -- 제식은 x -  a
  145. a = arg[1]
  146. c = { }
  147. s = { }
  148. b = { }
  149. for i = 1, #arg-1 do
  150.     c[i] = tonumber(arg[i + 1])
  151. end
  152. -- 조립제법의 주요 부분
  153. s[1] = 0.0
  154. b[1] = c[1]
  155. for i = 2, #c do
  156.     s[i] = b[i-1]*a
  157.     b[i] = c[i] + s[i]
  158. end
  159. -- 몫의 계수와 나머지를 출력한다.
  160. io.write("몫의 계수는 ")
  161. for i = 1, #b-1 do
  162.     io.write(simplify(b[i], nil) .. ", ");
  163. end
  164. io.write(simplify(b[#b], nil) .. " ")
  165. io.write("이고, 나머지는 " .. simplify(b[#b], nil) .. " 이다." .. "\n")
  166. io.write("\n")
  167. -- 조립제법 표를 출력한다.
  168. printSyntheticTable(a, c, s, b)
  169. io.write("\n")
  170. -- (피제식) = (제식) x (몫) + (나머지)
  171. printDivisionResult(a, c, b)




실행> lua testSyntheticDivision.lua 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 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Ruby 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

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

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

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


아래의 소스파일은 Python용 소스파일 testSyntheticDivision.py 를 Ruby용으로 수정한 것이다.

ruby 대신 jruby 로도 수정 없이 그대로 실행된다.


  1. =begin
  2.   Filename: testSyntheticDivision.rb
  3.   Purpose:  Find the quotient and remainder when some polynomial is
  4.             divided by a monic polynomial of the first degree.
  5.   Execute:  ruby testSyntheticDivision.rb -2 1 3 3 1
  6.         Or  jruby testSyntheticDivision.rb -2 1 3 3 1
  7. =end
  8. # 사용법 표시
  9. def printUsage()
  10.     print("사용법: ruby testSyntheticDivision.rb [수] [피제식의 계수들]" + "\n")
  11.     print("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다." + "\n")
  12. end
  13. # 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  14. # 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  15. def simplify(v, width)
  16.     t = "%d" % v
  17.     tlen = t.length
  18.     if t[(tlen-2)..(tlen-1)] == ".0"
  19.         t = t[0..(tlen-2)]
  20.     end
  21.     if width != nil
  22.         if tlen < width
  23.             t = "              "[0...(width - tlen)] + t
  24.         end
  25.     end
  26.     return t
  27. end
  28. # 다항식을 내림차순의 스트링 표현으로 반환
  29. def toPolyString(c)
  30.     t = ""
  31.     sc0 = simplify(c[0], nil)
  32.     if c.length > 2
  33.         if sc0 == "1"
  34.             t += "x^%d" % (c.length-1)
  35.         elsif sc0 == "-1"
  36.             t += "-x^%d" % (c.length-1)
  37.         else
  38.             t += sc0 + " x^%d" % (c.length-1)
  39.         end
  40.     elsif c.length == 2
  41.         if sc0 == "1"
  42.             t += "x"
  43.         elsif sc0 == "-1"
  44.             t += "-x"
  45.         else
  46.             t += sc0 + " x"
  47.         end
  48.     elsif c.length == 1
  49.         t += sc0
  50.     end
  51.     for i in 1...c.length do
  52.         k = c.length - 1 - i
  53.         sc = simplify(c[i], nil)
  54.         if k > 1
  55.             if c[i] > 0.0
  56.                 if sc == "1"
  57.                     t += " + " + "x^" + k
  58.                 else
  59.                     t += " + " + sc + " x^%d" % k
  60.                 end
  61.             elsif c[i] < 0.0
  62.                 if sc == "-1"
  63.                     t += " - " + "x^" + k
  64.                 else
  65.                     t += " - " + simplify(c[i].abs, nil) + " x^%d" % k
  66.                 end
  67.             end
  68.         elsif k == 1
  69.             if c[i] > 0.0
  70.                 if sc == "1"
  71.                     t += " + " + "x"
  72.                 else
  73.                     t += " + " + sc + " x"
  74.                 end
  75.             elsif c[i] < 0.0
  76.                 if sc == "-1"
  77.                     t += " - " + "x"
  78.                 else
  79.                     t += " - " + simplify(c[i].abs, nil) + " x"
  80.                 end
  81.             end
  82.         elsif k == 0
  83.             if c[i] > 0.0
  84.                 t += " + " + sc
  85.             elsif c[i] < 0.0
  86.                 t += " - " + simplify(c[i].abs, nil)
  87.             end
  88.         end
  89.     end
  90.     return t
  91. end
  92. # 다향식 나눗셈 결과를
  93. #     (피제식) = (제식)(몫) + (나마지)
  94. # 형태로 출력
  95. def printDivisionResult(a, c, b)
  96.     strLine = "  " + toPolyString(c)
  97.     print( strLine + "\n")
  98.     strLine = "    = ( " + toPolyString( [1.0, -a] ) + " )"
  99.     tmp = [0.0] * (b.length - 1)
  100.     for i in 0...tmp.length do
  101.         tmp[i] = b[i]
  102.     end
  103.     strLine += "( " + toPolyString(tmp) + " )"
  104.     r = b[b.length - 1]
  105.     if r > 0.0
  106.         strLine += " + " + simplify(r, nil)
  107.     elsif r < 0.0
  108.         strLine += " - " + simplify(r.abs, nil)
  109.     end
  110.     print( strLine + "\n" )
  111. end
  112. # 조립제법 계산표 출력 함수
  113. def printSyntheticTable(a, c, s, q)
  114.     strLine = "       | "
  115.     strLine += simplify(c[0], 6)
  116.     for i in 1...c.length do
  117.         strLine += "  " + simplify(c[i], 6)
  118.     end
  119.     print( strLine + "\n" )
  120.     strLine = simplify(a, 6) + " |"
  121.     strLine += "         "
  122.     strLine += simplify(s[1], 6)
  123.     for i in 2...s.length do
  124.         strLine += "  " + simplify(s[i], 6)
  125.     end
  126.     print( strLine + "\n" )
  127.     strLine = "       |"
  128.     for i in 0...q.length do
  129.         strLine += "--------"
  130.     end
  131.     print( strLine + "\n" )
  132.     strLine = "         "
  133.     strLine += simplify(q[0], 6)
  134.     for i in 1...q.length do
  135.         strLine += "  " + simplify(q[i], 6)
  136.     end
  137.     print( strLine + "\n" )
  138. end
  139. # 실행 시작 지점
  140. if ARGV.length < 2
  141.     printUsage()
  142.     exit(1)
  143. end
  144. ######################################################
  145. # 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  146. # 제식은 x -  a
  147. a = ARGV[0].to_f
  148. c = [0.0]*(ARGV.length - 1)
  149. s = [0.0]*(+ARGV.length - 1)
  150. b = [0.0]*(ARGV.length - 1)
  151. for i in 0...c.length do
  152.     c[i] = ARGV[i + 1].to_f
  153. end
  154. ######################################################
  155. # 조립제법의 주요 부분
  156. s[0] = 0.0
  157. b[0] = c[0]
  158. for i in 1...c.length do
  159.     s[i] = b[i-1]*a
  160.     b[i] = c[i] + s[i]
  161. end
  162. ######################################################
  163. # 몫의 계수와 나머지를 출력한다.
  164. print("몫의 계수는 ")
  165. for i in 0...(b.length - 2) do
  166.     print(simplify(b[i], nil) + ", " )
  167. end
  168. print(simplify(b[b.length - 2], nil) + " ")
  169. print("이고, 나머지는 " + simplify(b[b.length - 1], nil) + " 이다." + "\n")
  170. print("\n")
  171. ######################################################
  172. # 조립제법 표를 출력한다.
  173. printSyntheticTable(a, c, s, b)
  174. print("\n")
  175. ######################################################
  176. # (피제식) = (제식) x (몫) + (나머지)
  177. printDivisionResult(a, c, b)




실행> ruby testSyntheticDivision.rb 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 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Python 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

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

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

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


아래의 소스파일은 Groovy용 소스파일 testSyntheticDivision.groovy 를 Python용으로 수정한 것이다.

python 대신 jython이나 IronPython 으로도 수정 없이 그대로 실행된다.


  1. #  Filename: testSyntheticDivision.py
  2. #
  3. #  Purpose:  Find the quotient and remainder when some polynomial is
  4. #            divided by a monic polynomial of the first degree.
  5. #
  6. #  Execute:  python testSyntheticDivision.py -2 1 3 3 1
  7. #        Or  jython testSyntheticDivision.py -2 1 3 3 1
  8. import sys
  9. # 사용법 표시
  10. def printUsage():
  11.     print("사용법: python testSyntheticDivision.py [수] [피제식의 계수들]")
  12.     print("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.")
  13. # 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  14. # 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  15. def simplify(v, width=None):
  16.     t = "%d" % v
  17.     tlen = len(t)
  18.     if t[tlen-2:tlen-1] == ".0":
  19.         t = t[0, -2]
  20.     if width != None:
  21.         if tlen < width:
  22.             t = "              "[0: width - tlen] + t
  23.     return t
  24. # 다항식을 내림차순의 스트링 표현으로 반환
  25. def toPolyString(c):
  26.     t = ""
  27.     sc0 = simplify(c[0])
  28.     if len(c) > 2:
  29.         if sc0 == "1":
  30.             t += "x^%d" % (len(c)-1)
  31.         elif sc0 == "-1":
  32.             t += "-x^%d" % (len(c)-1)
  33.         else:
  34.             t += sc0 + " x^%d" % (len(c)-1)
  35.     elif len(c) == 2:
  36.         if sc0 == "1":
  37.             t += "x"
  38.         elif sc0 == "-1":
  39.             t += "-x"
  40.         else:
  41.             t += sc0 + " x"
  42.     elif len(c) == 1:
  43.         t += sc0
  44.     for i in range(1, len(c)):
  45.         k = len(c) - 1 - i
  46.         sc = simplify(c[i])
  47.         if k > 1:
  48.             if c[i] > 0.0:
  49.                 if sc == "1":
  50.                     t += " + " + "x^%d" % k
  51.                 else:
  52.                     t += " + " + sc + " x^%d" % k
  53.             elif c[i] < 0.0:
  54.                 if sc == "-1":
  55.                     t += " - " + "x^%d" % k
  56.                 else:
  57.                     t += " - " + simplify(abs(c[i])) + " x^%d" % k
  58.         elif k == 1:
  59.             if c[i] > 0.0:
  60.                 if sc == "1":
  61.                     t += " + " + "x"
  62.                 else:
  63.                     t += " + " + sc + " x"
  64.             elif c[i] < 0.0:
  65.                 if sc == "-1":
  66.                     t += " - " + "x"
  67.                 else:
  68.                     t += " - " + simplify(abs(c[i])) + " x"
  69.         elif k == 0:
  70.             if c[i] > 0.0:
  71.                 t += " + " + sc
  72.             elif c[i] < 0.0:
  73.                 t += " - " + simplify(abs(c[i]))
  74.     return t
  75. # 다항식 나눗셈 결과를
  76. #     (피제식) = (제식)(몫) + (나머지)
  77. # 형태로 출력
  78. def printDivisionResult(a, c, b):
  79.     strLine = "  " + toPolyString(c)
  80.     print( strLine )
  81.     strLine = "    = ( " + toPolyString( [1.0, -a] ) + " )"
  82.     tmp = [0.0] * (len(b) - 1)
  83.     for i in range(0, len(tmp)):
  84.         tmp[i] = b[i]
  85.     strLine += "( " + toPolyString(tmp) + " )"
  86.     r = b[len(b) - 1]
  87.     if r > 0.0:
  88.         strLine += " + " + simplify(r)
  89.     elif r < 0.0:
  90.         strLine += " - " + simplify(abs(r))
  91.     print( strLine )
  92. # 조립제법 계산표 출력 함수
  93. def printSyntheticTable(a, c, s, q):
  94.     strLine = "       | "
  95.     strLine += simplify(c[0], 6)
  96.     for i in range(1, len(c)):
  97.         strLine += "  " + simplify(c[i], 6)
  98.     print( strLine )
  99.     strLine = simplify(a, 6) + " |"
  100.     strLine += "         "
  101.     strLine += simplify(s[1], 6)
  102.     for i in range(2, len(s)):
  103.         strLine += "  " + simplify(s[i], 6)
  104.     print( strLine )
  105.     strLine = "       |"
  106.     for i in range(0, len(q)):
  107.         strLine += "--------"
  108.     print( strLine )
  109.     strLine = "         "
  110.     strLine += simplify(q[0], 6)
  111.     for i in range(1, len(q)):
  112.         strLine += "  " + simplify(q[i], 6)
  113.     print( strLine )
  114. # 실행 시작 지점
  115. if len(sys.argv) < 3:
  116.     printUsage()
  117.     sys.exit(1)
  118. ######################################################
  119. # 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  120. # 제식은 x -  a
  121. a = float(sys.argv[1])
  122. c = [0.0]*(len(sys.argv) - 2)
  123. s = [0.0]*(len(sys.argv) - 2)
  124. b = [0.0]*(len(sys.argv) - 2)
  125. for i in range(0, len(c)):
  126.     c[i] = float(sys.argv[i + 2])
  127. ######################################################
  128. # 조립제법의 주요 부분
  129. s[0] = 0.0
  130. b[0] = c[0]
  131. for i in range(1, len(c)):
  132.     s[i] = b[i-1]*a
  133.     b[i] = c[i] + s[i]
  134. ######################################################
  135. # 몫의 계수와 나머지를 출력한다.
  136. print("몫의 계수는"),
  137. for i in range(0, len(b) - 2):
  138.     print(simplify(b[i], None) + ", " ),
  139. print(simplify(b[len(b) - 2], None)),
  140. print("이고, 나머지는 " + simplify(b[len(b) - 1], None) + " 이다.")
  141. print
  142. ######################################################
  143. # 조립제법 표를 출력한다.
  144. printSyntheticTable(a, c, s, b)
  145. print
  146. ######################################################
  147. # (피제식) = (제식) x (몫) + (나머지)
  148. printDivisionResult(a, c, b)




실행> python testSyntheticDivision.py 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
,
다항식 p(x) 를 1차 다항식 x - a 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Groovy 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

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

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

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



  1. /*
  2.  *  Filename: testSyntheticDivision.groovy
  3.  *
  4.  *  Purpose:  Find the quotient and remainder when some polynomial is
  5.  *            divided by a monic polynomial of the first degree.
  6.  *     이 소스는 자바 소스 TestSyntheticMethod.java 와 내용이 거의 같은
  7.  *    그루비 소스 TestSyntheticMethod.groovy 를 더욱 그루비 소스 코드 답게 수정한 것이다.
  8.  *
  9.  *  Execute: groovy testSyntheticDivision.groovy -2 1 3 3 1
  10.  *
  11.  */
  12. // 사용법 표시
  13. def printUsage() {
  14.      println("사용법: groovy testSyntheticDivision.groovy [수] [피제식의 계수들]")
  15.      println("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.")
  16. }
  17. // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  18. String simplify(double v) {
  19.     String t = "" + v
  20.     if (t.endsWith(".0"))
  21.         t = t[0..<(t.length() - 2)]
  22.     return t
  23. }
  24. // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  25. // 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  26. String simplify(double v, int width) {
  27.     String t = "" + v
  28.     if (t.endsWith(".0"))
  29.         t = t[0..<(t.length() - 2)]
  30.     int len = t.length()
  31.     if (len < width)
  32.         t = "               ".substring(0, width - len) + t
  33.     return t;
  34. }
  35. // 다항식을 내림차순의 스트링 표현으로 반환
  36. String toPolyString(double[] c) {
  37.     String t = ""
  38.     def sc0 = simplify(c[0])
  39.     if (c.length > 2) {
  40.         if (sc0 == "1")
  41.             t += "x^" + (c.length-1)
  42.         else if (sc0 == "-1")
  43.             t += "-x^" + (c.length-1)
  44.         else
  45.             t += sc0 + " x^" + (c.length-1)
  46.     }
  47.     else if (c.length == 2) {
  48.         if (sc0 == "1")
  49.             t += "x"
  50.         else if (sc0 == "-1")
  51.             t += "-x"
  52.         else
  53.             t += sc0 + " x"
  54.     }
  55.     else if (c.length == 1) {
  56.         t += sc0
  57.     }
  58.     for (i in 1..< c.length) {
  59.         def k = c.length - 1 - i
  60.         def sc = simplify(c[i])
  61.         if (k > 1) {
  62.             if (c[i] > 0.0) {
  63.                 if (sc == "1")
  64.                     t += " + " + "x^" + k
  65.                 else
  66.                     t += " + " + sc + " x^" + k
  67.             }
  68.             else if (c[i] < 0.0) {
  69.                 if (sc == "-1")
  70.                     t += " - " + "x^" + k
  71.                 else
  72.                     t += " - " + simplify(Math.abs(c[i])) + " x^" + k
  73.             }
  74.         }
  75.         else if (k == 1) {
  76.             if (c[i] > 0.0) {
  77.                 if (sc == "1")
  78.                     t += " + " + "x"
  79.                 else
  80.                     t += " + " + sc + " x"
  81.             }
  82.             else if (c[i] < 0.0) {
  83.                 if (sc == "-1")
  84.                     t += " - " + "x"
  85.                 else
  86.                     t += " - " + simplify(Math.abs(c[i])) + " x"
  87.             }
  88.         }
  89.         else if (k == 0) {
  90.             if (c[i] > 0.0) {
  91.                 t += " + " + sc
  92.             }
  93.             else if (c[i] < 0.0)
  94.                 t += " - " + simplify(Math.abs(c[i]))
  95.         }
  96.     }
  97.     return t
  98. }
  99. // 다항식 나눗셈 결과를
  100. //     (피제식) = (제식)(몫) + (나마지)
  101. // 형태로 출력
  102. def printDivisionResult(double a, double[] c, double[] b) {
  103.     print("  " + toPolyString(c))
  104.     println()
  105.     print("    = ( " + toPolyString( [1.0, -a] as double[] ) + " )")
  106.     double[] tmp = new double[b.length - 1]
  107.     for (i in 0..<tmp.length) {
  108.         tmp[i] = b[i]
  109.     }
  110.     print("( " + toPolyString(tmp) + " )")
  111.     double r = b[b.length - 1]
  112.     if (r > 0.0)
  113.         print(" + " + simplify(r))
  114.     else if (r < 0.0)
  115.         print(" - " + simplify(Math.abs(r)))
  116.     println()
  117. }
  118. // 조립제법 계산표 출력 함수
  119. def printSyntheticTable(double a, double[] c, double[] s, double[] q) {
  120.     print("       | ")
  121.     print(simplify(c[0], 6))
  122.     for (i in 1..< c.length) {
  123.         print("  " + simplify(c[i], 6))
  124.     }
  125.     println()
  126.     print(simplify(a, 6) + " | ")
  127.     print("        ")
  128.     print(simplify(s[1], 6))
  129.     for (i in 2..< s.length) {
  130.         print("  " + simplify(s[i], 6))
  131.     }
  132.     println()
  133.     print("       |-")
  134.     for (i in 0..< q.length) {
  135.         print("--------")
  136.     }
  137.     println()
  138.     print("         ")
  139.     print(simplify(q[0], 6))
  140.     for (i in 1..< q.length) {
  141.         print("  " + simplify(q[i], 6))
  142.     }
  143.     println()
  144. }
  145. // 실행 시작 지점
  146. if (args.length < 3) {
  147.     printUsage()
  148.     System.exit(1);
  149. }
  150. double a = Double.parseDouble(args[0])
  151. double[] c = new double[args.length - 1]
  152. double[] s = new double[c.length]
  153. double[] b = new double[c.length]
  154. for (i in 0..<c.length) {
  155.     c[i] = Double.parseDouble(args[i + 1])
  156. }
  157. s[0] = 0.0;
  158. b[0] = c[0];
  159. for (i in 1..<c.length) {
  160.     s[i] = b[i-1]*a
  161.  b[i] = c[i] + s[i]
  162. }
  163. print("몫의 계수는 ");
  164. for (i in 0..<(b.length - 2)) {
  165.     print(simplify(b[i]) + ", " )
  166. }
  167. print(simplify(b[b.length - 2]))
  168. println(" 이고, 나머지는 " + simplify(b[b.length - 1]) + " 이다.")
  169. println()
  170. printSyntheticTable(a, c, s, b)
  171. println()
  172. printDivisionResult(a, c, b)



groovy 명령으로 아래와 같이 실행하여 보았다.


실행> groovy testSyntheticDivision.groovy 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 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Groovy 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

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

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


  1. /*
  2.  *  Filename: TestSyntheticMethod.groovy
  3.  *
  4.  *  Purpose:  Find the quotient and remainder when some polynomial is
  5.  *                 divided by a monic polynomial of the first degree.
  6.  *     이 소스는 자바소스 TestSyntheticMethod.java 에서 배열 생성 부분
  7.  *     new double[] {1.0, -a} 을 [1.0, -a] as double[] 로 변경한 것만 다르다.
  8.  *
  9.  *  Execute: groovy TestSyntheticMethod.groovy -2 1 3 3 1
  10.  */
  11. import java.lang.Math;
  12. public class TestSyntheticMethod {
  13.     // 사용법 표시
  14.     public static void printUsage() {
  15.          System.out.println("사용법: java TestSyntheticMethod [수] [피제식의 계수들]");
  16.          System.out.println("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.");
  17.     }
  18.     // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  19.     public static String simplify(double v) {
  20.         String t = "" + v;
  21.         if (t.endsWith(".0"))
  22.             t = t.substring(0, t.length() - 2);
  23.         return t;
  24.     }
  25.     // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  26.     // 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  27.     public static String simplify(double v, int width) {
  28.         String t = "" + v;
  29.         if (t.endsWith(".0"))
  30.             t = t.substring(0, t.length() - 2);
  31.         int len = t.length();
  32.         if (len < width)
  33.             t = "               ".substring(0, width - len) + t;
  34.         return t;
  35.     }
  36.     // 다항식을 내림차순의 스트링 표현으로 반환
  37.     public static String toPolyString(double[] c) {
  38.         String t = "";
  39.         if (c.length > 2) {
  40.             if (simplify(c[0]).equals("1"))
  41.                 t += "x^" + (c.length-1);
  42.             else if (simplify(c[0]).equals("-1"))
  43.                 t += "-x^" + (c.length-1);
  44.             else
  45.                 t += simplify(c[0]) + " x^" + (c.length-1);
  46.         }
  47.         else if (c.length == 2) {
  48.             if (simplify(c[0]).equals("1"))
  49.                 t += "x";
  50.             else if (simplify(c[0]).equals("-1"))
  51.                 t += "-x";
  52.             else
  53.                 t += simplify(c[0]) + " x";
  54.         }
  55.         else if (c.length == 1) {
  56.             t += simplify(c[0]);
  57.         }
  58.         for (int i = 1; i < c.length; i++) {
  59.             if (c.length - 1 - i > 1) {
  60.                 if (c[i] > 0.0) {
  61.                     if (simplify(c[i]).equals("1"))
  62.                         t += " + " + "x^" + (c.length - 1 - i);
  63.                     else
  64.                         t += " + " + simplify(c[i]) + " x^" + (c.length - 1 - i);
  65.                 }
  66.                 else if (c[i] < 0.0) {
  67.                     if (simplify(c[i]).equals("-1"))
  68.                         t += " - " + "x^" + (c.length - 1 - i);
  69.                     else
  70.                         t += " - " + simplify(Math.abs(c[i])) + " x^" + (c.length - 1 - i);
  71.                 }
  72.             }
  73.             else if (c.length - 1 - i == 1) {
  74.                 if (c[i] > 0.0) {
  75.                     if (simplify(c[i]).equals("1"))
  76.                         t += " + " + "x";
  77.                     else
  78.                         t += " + " + simplify(c[i]) + " x";
  79.             }
  80.             else if (c[i] < 0.0) {
  81.                 if (simplify(c[i]).equals("-1"))
  82.                     t += " - " + "x";
  83.                 else
  84.                     t += " - " + simplify(Math.abs(c[i])) + " x";
  85.             }
  86.         }
  87.         else if (c.length - 1 - i == 0) {
  88.             if (c[i] > 0.0) {
  89.                 t += " + " + simplify(c[i]);
  90.             }
  91.             else if (c[i] < 0.0)
  92.                 t += " - " + simplify(Math.abs(c[i]));
  93.             }
  94.         }
  95.         return t;
  96.     }
  97.     // 다항식 나눗셈 결과를
  98.     //     (피제식) = (제식)(몫) + (나마지)
  99.     // 형태로 출력
  100.     public static void printDivisionResult(double a, double[] c, double[] b) {
  101.         System.out.print("  " + toPolyString(c));
  102.         System.out.println();
  103.         System.out.print("    = ( " + toPolyString( [1.0, -a] as double[] ) + " )");
  104.         double[] tmp = new double[b.length - 1];
  105.         for (int i = 0; i < tmp.length; i++) {
  106.             tmp[i] = b[i];
  107.         }
  108.         System.out.print("( " + toPolyString(tmp) + " )");
  109.         double r = b[b.length - 1];
  110.         if (r > 0.0)
  111.             System.out.print(" + " + simplify(r));
  112.         else if (r < 0.0)
  113.             System.out.print(" - " + simplify(Math.abs(r)));
  114.         System.out.println();
  115.     }
  116.     // 조립제법 계산표 출력 메소드
  117.     public static void printSyntheticTable(double a, double[] c, double[] s, double[] q) {
  118.         System.out.print("       | ");
  119.         System.out.print(simplify(c[0], 6));
  120.         for (int i = 1; i < c.length; i++) {
  121.             System.out.print("  " + simplify(c[i], 6));
  122.         }
  123.         System.out.println();
  124.         System.out.print(simplify(a, 6) + " | ");
  125.         System.out.print("        ");
  126.         System.out.print(simplify(s[1], 6));
  127.         for (int i = 2; i < s.length; i++) {
  128.             System.out.print("  " + simplify(s[i], 6));
  129.         }
  130.         System.out.println();
  131.         System.out.print("       |-");
  132.         for (int i = 0; i < q.length; i++) {
  133.             System.out.print("--------");
  134.         }
  135.         System.out.println("");
  136.         System.out.print("         ");
  137.         System.out.print(simplify(q[0], 6));
  138.         for (int i = 1; i < q.length; i++) {
  139.             System.out.print("  " + simplify(q[i], 6));
  140.         }
  141.         System.out.println();
  142.     }
  143.     // Java 애플리케이션의 실행 시작 시점 main 메소드
  144.     // (C 언어의 main 함수에 해당)
  145.     public static void main(String[] args) {
  146.         if (args.length < 3) {
  147.             printUsage();
  148.             System.exit(1);
  149.         }
  150.         //////////////////////////////////////////////////////
  151.         // 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  152.         // 제식은 x -  a
  153.         double a = Double.parseDouble(args[0]);
  154.         double[] c = new double[args.length - 1];
  155.         double[] s = new double[c.length];
  156.         double[] b = new double[c.length];
  157.         for (int i = 0; i < c.length; i++) {
  158.             c[i] = Double.parseDouble(args[i + 1]);
  159.         }
  160.         //////////////////////////////////////////////////////
  161.         // 조립제법의 주요 부분
  162.         s[0] = 0.0;
  163.         b[0] = c[0];
  164.         for (int i = 1; i < c.length; i++) {
  165.            s[i] = b[i-1]*a;
  166.             b[i] = c[i] + s[i];
  167.         }
  168.         //////////////////////////////////////////////////////
  169.         // 몫의 계수와 나머지를 출력한다.
  170.         System.out.print("몫의 계수는 ");
  171.         for (int i = 0; i < b.length - 2; i++) {
  172.             System.out.print(simplify(b[i]) + ", " );
  173.         }
  174.         System.out.print(simplify(b[b.length - 2]));
  175.         System.out.println(" 이고, 나머지는 " + simplify(b[b.length - 1]) + " 이다.");
  176.         System.out.println();
  177.         //////////////////////////////////////////////////////
  178.         // 조립제법 표를 출력한다.
  179.         printSyntheticTable(a, c, s, b);
  180.         System.out.println();
  181.         //////////////////////////////////////////////////////
  182.         // (피제식) = (제식) x (몫) + (나머지)
  183.         printDivisionResult(a, c, b);
  184.     }
  185. }



Groovy 언어로 작성된 소스파일은 groovyc 명형으로 컴파일한 후 , 컴파일된 .class 파일을 java 명령으로 실행해도 되지만, groovy 명령을 사용하여 (아래에서 처험) 컴파일 과정 없이 직접 소스파일을 실행시킬 수 있다.


실행> groovy TestSyntheticMethod.groovy 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 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Java 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

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

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

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

  1. /*
  2.  *  Filename: TestSyntheticMethod.java
  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: javac -d . TestSyntheticMethod.java
  8.  *
  9.  *  Execute: java TestSyntheticMethod -2 1 3 3 1
  10.  */
  11. import java.lang.Math;
  12. public class TestSyntheticMethod {
  13.     // 사용법 표시
  14.     public static void printUsage() {
  15.          System.out.println("사용법: java TestSyntheticMethod [수] [피제식의 계수들]");
  16.          System.out.println("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.");
  17.     }
  18.     // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  19.     public static String simplify(double v) {
  20.         String t = "" + v;
  21.         if (t.endsWith(".0"))
  22.             t = t.substring(0, t.length() - 2);
  23.         return t;
  24.     }
  25.     // 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  26.     // 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  27.     public static String simplify(double v, int width) {
  28.         String t = "" + v;
  29.         if (t.endsWith(".0"))
  30.             t = t.substring(0, t.length() - 2);
  31.         int len = t.length();
  32.         if (len < width)
  33.             t = "               ".substring(0, width - len) + t;
  34.         return t;
  35.     }
  36.     // 다항식을 내림차순의 스트링 표현으로 반환
  37.     public static String toPolyString(double[] c) {
  38.         String t = "";
  39.         if (c.length > 2) {
  40.             if (simplify(c[0]).equals("1"))
  41.                 t += "x^" + (c.length-1);
  42.             else if (simplify(c[0]).equals("-1"))
  43.                 t += "-x^" + (c.length-1);
  44.             else
  45.                 t += simplify(c[0]) + " x^" + (c.length-1);
  46.         }
  47.         else if (c.length == 2) {
  48.             if (simplify(c[0]).equals("1"))
  49.                 t += "x";
  50.             else if (simplify(c[0]).equals("-1"))
  51.                 t += "-x";
  52.             else
  53.                 t += simplify(c[0]) + " x";
  54.         }
  55.         else if (c.length == 1) {
  56.             t += simplify(c[0]);
  57.         }
  58.         for (int i = 1; i < c.length; i++) {
  59.             if (c.length - 1 - i > 1) {
  60.                 if (c[i] > 0.0) {
  61.                     if (simplify(c[i]).equals("1"))
  62.                         t += " + " + "x^" + (c.length - 1 - i);
  63.                     else
  64.                         t += " + " + simplify(c[i]) + " x^" + (c.length - 1 - i);
  65.                 }
  66.                 else if (c[i] < 0.0) {
  67.                     if (simplify(c[i]).equals("-1"))
  68.                         t += " - " + "x^" + (c.length - 1 - i);
  69.                     else
  70.                         t += " - " + simplify(Math.abs(c[i])) + " x^" + (c.length - 1 - i);
  71.                 }
  72.             }
  73.             else if (c.length - 1 - i == 1) {
  74.                 if (c[i] > 0.0) {
  75.                     if (simplify(c[i]).equals("1"))
  76.                         t += " + " + "x";
  77.                     else
  78.                         t += " + " + simplify(c[i]) + " x";
  79.             }
  80.             else if (c[i] < 0.0) {
  81.                 if (simplify(c[i]).equals("-1"))
  82.                     t += " - " + "x";
  83.                 else
  84.                     t += " - " + simplify(Math.abs(c[i])) + " x";
  85.             }
  86.         }
  87.         else if (c.length - 1 - i == 0) {
  88.             if (c[i] > 0.0) {
  89.                 t += " + " + simplify(c[i]);
  90.             }
  91.             else if (c[i] < 0.0)
  92.                 t += " - " + simplify(Math.abs(c[i]));
  93.             }
  94.         }
  95.         return t;
  96.     }
  97.     // 다항식 나눗셈 결과를
  98.     //     (피제식) = (제식)(몫) + (나마지)
  99.     // 형태로 출력
  100.     public static void printDivisionResult(double a, double[] c, double[] b) {
  101.         System.out.print("  " + toPolyString(c));
  102.         System.out.println();
  103.         System.out.print("    = ( " + toPolyString( new double[] {1.0, -a} ) + " )");
  104.         double[] tmp = new double[b.length - 1];
  105.         for (int i = 0; i < tmp.length; i++) {
  106.             tmp[i] = b[i];
  107.         }
  108.         System.out.print("( " + toPolyString(tmp) + " )");
  109.         double r = b[b.length - 1];
  110.         if (r > 0.0)
  111.             System.out.print(" + " + simplify(r));
  112.         else if (r < 0.0)
  113.             System.out.print(" - " + simplify(Math.abs(r)));
  114.         System.out.println();
  115.     }
  116.     // 조립제법 계산표 출력 메소드
  117.     public static void printSyntheticTable(double a, double[] c, double[] s, double[] q) {
  118.         System.out.print("       | ");
  119.         System.out.print(simplify(c[0], 6));
  120.         for (int i = 1; i < c.length; i++) {
  121.             System.out.print("  " + simplify(c[i], 6));
  122.         }
  123.         System.out.println();
  124.         System.out.print(simplify(a, 6) + " | ");
  125.         System.out.print("        ");
  126.         System.out.print(simplify(s[1], 6));
  127.         for (int i = 2; i < s.length; i++) {
  128.             System.out.print("  " + simplify(s[i], 6));
  129.         }
  130.         System.out.println();
  131.         System.out.print("       |-");
  132.         for (int i = 0; i < q.length; i++) {
  133.             System.out.print("--------");
  134.         }
  135.         System.out.println("");
  136.         System.out.print("         ");
  137.         System.out.print(simplify(q[0], 6));
  138.         for (int i = 1; i < q.length; i++) {
  139.             System.out.print("  " + simplify(q[i], 6));
  140.         }
  141.         System.out.println();
  142.     }
  143.     // Java 애플리케이션의 실행 시작 시점 main 메소드
  144.     // (C 언어의 main 함수에 해당)
  145.     public static void main(String[] args) {
  146.         if (args.length < 3) {
  147.             printUsage();
  148.             System.exit(1);
  149.         }
  150.         //////////////////////////////////////////////////////
  151.         // 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  152.         // 제식은 x -  a
  153.         double a = Double.parseDouble(args[0]);
  154.         double[] c = new double[args.length - 1];
  155.         double[] s = new double[c.length];
  156.         double[] b = new double[c.length];
  157.         for (int i = 0; i < c.length; i++) {
  158.             c[i] = Double.parseDouble(args[i + 1]);
  159.         }
  160.         //////////////////////////////////////////////////////
  161.         // 조립제법의 주요 부분
  162.         s[0] = 0.0;
  163.         b[0] = c[0];
  164.         for (int i = 1; i < c.length; i++) {
  165.            s[i] = b[i-1]*a;
  166.             b[i] = c[i] + s[i];
  167.         }
  168.         //////////////////////////////////////////////////////
  169.         // 몫의 계수와 나머지를 출력한다.
  170.         System.out.print("몫의 계수는 ");
  171.         for (int i = 0; i < b.length - 2; i++) {
  172.             System.out.print(simplify(b[i]) + ", " );
  173.         }
  174.         System.out.print(simplify(b[b.length - 2]));
  175.         System.out.println(" 이고, 나머지는 " + simplify(b[b.length - 1]) + " 이다.");
  176.         System.out.println();
  177.         //////////////////////////////////////////////////////
  178.         // 조립제법 표를 출력한다.
  179.         printSyntheticTable(a, c, s, b);
  180.         System.out.println();
  181.         //////////////////////////////////////////////////////
  182.         // (피제식) = (제식) x (몫) + (나머지)
  183.         printDivisionResult(a, c, b);
  184.     }
  185. }





컴파일> javac -d . TestSyntheticMethod.java
실행> java TestSyntheticMethod 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
,

D 언어의 if ... else ... 조건문 구문은 C/C++/Java/Groovy 의 것과 같다.
단, 한글이 포함된 소스파일은 UTF-8 인코딩으로 저장해야 한다.
또 C/C++ 언어에서 쓰이는 exit() 함수를 D 언어에서 쓰기 위해서는

        import std.c.stdlib;

구문을 소스의 앞부분에 미리 써 놓아야 한다.


소스 파일명: testIfD.d

  1. import std.c.stdio;    // printf 함수 사용을 위해
  2. import std.c.stdlib;    // exit 함수 사용을 위해
  3. import std.conv;        // to! 변환함수 사용을 위해
  4. // 사용법을 컨솔에 보여주는 함수
  5. void printUsing() {
  6.     printf("Using: testIfD [number]\n");
  7.     printf("This determines whether the number is positive or not.\n");
  8. }
  9. int main (string[] args) {
  10.     float val;
  11.     if (args.length != 2) {
  12.         printUsing();
  13.         exit(1);
  14.         return 1;
  15.     }
  16.     // 명령행 인자의 스트링을 가져와서
  17.     // 배정밀도 부동소수점수로 변환하여
  18.     // 변수 val에 저장한다.
  19.     val = to!(float)(args[1]);
  20.     // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  21.     // 판단하는 if...else... 조건문
  22.     if (val > 0.0)
  23.         printf("%g is a positive number.\n", val);
  24.     else if (val < 0.0)
  25.         printf("%g is a negative number.\n", val);
  26.     else
  27.         printf("%g is zero.\n", val);
  28.     return 0;
  29. }

컴파일> dmd testIfD.d

실행> testIfD
Using: testIfD [number]
This determines whether the number is positive or not.

실행> testIfD 1.234
1.234 is a positive number.

실행> testIfD 1.234
-1.234 is a negative number.

실행> testIfD 0
0 is zero.



Posted by Scripter
,
소스에 한글이 포함된 경우에는 파일을 UTF-8 인코딩으로 저장해야 한다.
반복문은 for( ; ; ) 구문을 써도 되지만, 여기서는 foreach 구문을 사용하였다.


소스 파일명: testArgumentsD.d
  1. import std.c.stdio;  // prinf 함수의사용을 위해
  2. import std.conv;     // to! 변환함수 사용을 위해
  3. int main (string[] args) {
  4.     double sum = 0.0;    // 초기화
  5.     // 명령행 인자(command-line argument) 개수 출력
  6.     printf("Count of arguments: %d\n", args.length);
  7.     foreach (string arg; args[1 .. args.length]) {
  8.         // 스트링을 배정밀도 부동소수점수로 변환하여 누적
  9.         // sum += std.conv.to!(double)(arg);
  10.         sum += to!(double)(arg);
  11.     }
  12.     // 누적된 배정밀도 값을 출력
  13.     printf("The sum of arguments is %g\n", sum);
  14.     return 0;
  15. }


컴파일> dmd testArgumentsD.d

실행> testArgumentsD 1 2 3 4
Count of arguments: 5
The sum of arguments is 10

실행> testArgumentsD 1 2 3 4.1
Count of arguments: 5
The sum of arguments is 10.1

Posted by Scripter
,

D 언어에는 froeach를 사영하는 반목문도 있지만,
C/C++/Java 언어에서 쓰인 보총의 for ( ;  ;) 을 그대로 써도 된다.

 
소스 파일명: testForLoopD.d
------------------------------[소스 시작]
import std.c.stdio;

int main (string[] args) {
    int x;
    x = 2;
    for (int i = 1; i < 10; i++) {
        printf("%d x %d  = %d\n", x, i, x*i);
    }
    return 0;
}
------------------------------[소스 끝]


컴파일> dmd testForLoop.d

실행> testForLoop
2 x 1  = 2
2 x 2  = 4
2 x 3  = 6
2 x 4  = 8
2 x 5  = 10
2 x 6  = 12
2 x 7  = 14
2 x 8  = 16
2 x 9  = 18




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

Posted by Scripter
,

D 언어 홈페이지는 http://www.digitalmars.com/d/index.html 이다.

컨솔에 문자 출력하는 D 언어 구문은  C 언어의 것과 같다.

       printf(format,  ...);

 
소스 파일명: hello.d
------------------------------[소스 시작]
import std.c.stdio;

int main (string[] args) {
    printf("Hello, world!\n");
    return 0;
}
------------------------------[소스 끝]


컴파일> dmd hello.d

실행> hello
Hello, world!



Posted by Scripter
,