Visual BASIC 언어 소스:

REM ============================================================================
REM  Filename: TestHexView_03.vb
REM
REM   Compile: vbc TestHexView_03.vb
REM   Execute: TestHexView_03 [filename]
REM
REM  Date: 2013. 8. 6.
REM ============================================================================


Imports System.IO

Public Class HexViewUtil

    Shared Sub PrintUsage()
        Console.WriteLine("Usage: TestHexView_03 [filename]")
    End Sub

    Shared Function ToHex(c As Integer)
        Dim s As String = ""
        Dim x1, x2 As Integer

        x1 = (c And &HF0) >> 4
        x2 = c And &H0F
        If x1 < 10 Then
            s = s & Chr(x1 + Asc("0"))
        Else
            s = s & Chr((x1 - 10) + Asc("A"))
        End If
        If x2 < 10 Then
            s = s + Chr(x2 + Asc("0"))
        Else
            s = s + Chr((x2 - 10) + Asc("A"))
        End If
        ToHex = s
    End Function

    Shared Function ToHex8(n As Integer)
        Dim s As String = ""
        Dim x1, x2, x3, x4, x5, x6, x7, x8 As Integer

        x1 = (n And &HF0000000) >> 28
        x2 = (n And &HF000000) >> 24
        x3 = (n And &HF00000) >> 20
        x4 = (n And &HF0000) >> 16
        x5 = (n And &HF000) >> 12
        x6 = (n And &HF00) >> 8
        x7 = (n And &HF0) >> 4
        x8 = n And &H0F

        If x1 < 10 Then
            s = s & Chr(x1 + Asc("0"))
        Else
            s = s & Chr((x1 - 10) + Asc("A"))
        End If
        If x2 < 10 Then
            s = s + Chr(x2 + Asc("0"))
        Else
            s = s + Chr((x2 - 10) + Asc("A"))
        End If
        If x3 < 10 Then
            s = s + Chr(x3 + Asc("0"))
        Else
            s = s + Chr((x3 - 10) + Asc("A"))
        End If
        If x4 < 10 Then
            s = s + Chr(x4 + Asc("0"))
        Else
            s = s + Chr((x4 - 10) + Asc("A"))
        End If
        s = s + " "
        If x5 < 10 Then
            s = s + Chr(x5 + Asc("0"))
        Else
            s = s + Chr((x5 - 10) + Asc("A"))
        End If
        If x6 < 10 Then
            s = s + Chr(x6 + Asc("0"))
        Else
            s = s + Chr((x6 - 10) + Asc("A"))
        End If
        If x7 < 10 Then
            s = s + Chr(x7 + Asc("0"))
        Else
            s = s + Chr((x7 - 10) + Asc("A"))
        End If
        If x8 < 10 Then
            s = s + Chr(x8 + Asc("0"))
        Else
            s = s + Chr((x8 - 10) + Asc("A"))
        End If
        ToHex8 = s
    End Function


    Shared Sub Main(args() as String)
        Dim fname = ""

        If args.Length < 1 Then
         PrintUsage()
            Exit Sub 
        Else
            fname = args(0)
        End If


        If My.Computer.FileSystem.DirectoryExists(fname) Then
            Console.WriteLine("The path ""{0}"" is a directory.", fname)
            Exit Sub 
        End If

        If My.Computer.FileSystem.FileExists(fname) = False Then
            Console.WriteLine("The file ""{0}"" does not exist.", fname)
            Exit Sub  
        End If

         Dim info As New FileInfo(fname)

         Dim fsize As Long = info.Length
        Console.WriteLine("The size of the file ""{0}"" is {1}.", fname, fsize)
        Console.WriteLine()

        Dim inputFile = IO.File.Open(fname, IO.FileMode.Open)

        Dim bufferSize = 16
        Dim bytes = New Byte(bufferSize) {}

        Dim n = 0
        Dim m = 0
        Dim i = 0
        Dim j = 0
        Dim t = ""
        Dim c = 0

        While n < fsize
            m = inputFile.Read(bytes, 0, bufferSize)
            If n Mod 16 = 0 Then
                Console.Write("{0}: ", ToHex8(n))
            End If
            For i = 0 To m - 1
                c = bytes(i)
                If i = 7 Then
                    Console.Write("-{0}", ToHex(c))
                Else
                    Console.Write(" {0}", ToHex(c))
                End If
                If c - Asc(" ") < 0 Or c > &H7F Then
                    t = t + "."
                Else
                    t = t + Chr(c)
                End If
            Next i

            If m < 16 Then
                For j = 1 To 16 - m
                    Console.Write("   ")
                Next j
            End If
            Console.Write(" |{0}", t)
            t = ""
            If m < 16 Then
                For j = 1 To 16 - m
                    Console.Write(" ")
                Next j
            End If
            Console.WriteLine("|")

            n = n + m
        End While

        inputFile.Close()

        Console.WriteLine()
        Console.WriteLine("Read {0} bytes.", n)

    End Sub
End Class

 

실행 예 1> TestHexView_03 temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74-68 65 72 65 0A             |Hello there.    |

Read 12 bytes.

 

실행 예 2> TestHexView_03 myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00-06 50 65 72 73 6F 6E 07 31 |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02-00 03 49 00 03 61 67 65 4C |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74-4E 61 6D 65 74 00 12 4C 6A |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E-67 2F 53 74 72 69 6E 67 3B |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74-4E 61 6D 65 71 00 7E 00 01 |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74-00 05 4A 61 6D 65 73 74 00 |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71-00 7E 00 00 00 00 00 1E 74 |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77-61 6E 74 00 06 4B 65 6E 6F |..Obi-want..Keno|
0000 0080:  62 69                                           |bi              |

Read 130 bytes.

 

 

 

 

Posted by Scripter
,

음이 아닌 실수 A 의 평방근 sqrt(A) 를 구하는 Heron 의 방법:

        반복함수  g(x) = (x + A/x) / 2   를 이용

 

실수 A 의 n제곱근 root(n, A) 를 구하는 Newton-Raphson 의 방법

        반복함수  g(x) = ((n-1)*x + A/(x**(n - 1))) / n    를 이용

n = 2 인 경우에는 Newton-Raphson 의 방법이 Heron 의 방법과 동일하다.

(참조. http://en.wikipedia.org/wiki/Newton's_method )

 

Visual BASIC 언어에는 System 모듈에 지수 계산 함수 Math.Pow(double, double) 가 이미 구현되어 있다. 하지만 차후 필요한 데가 있을 것 같아서 이와 유사한 n 제곱 함수와 n 제곱근 함수를 구현해 보았다.

지수가 정수인 거듭제곱을 계산하는  함수도 nPow(), gPow, mPow() 세 개 구현해 놓았는데, 이들 세 함수는 절차적 언어의 성능상 재귀호출이 아니고 단순 반복 기법을 사용하는 함수이다. 이 세 함수 중 mPow() 의 성능이 가장 우수하다. 큰 지수의 경우 for 반복문의 반복회수를 따져 보면 성능 비교를 할 수 있을 것이다. (성능 비교를 위해 세 가지를 모두 소스에 남겨 두었다.) mPow() 함수는 n 제곱근을 구하는 재귀함수 newtonNthRoot(int, double) 의 구현에 사용되기도 한다. if ... else ... 구문이 많아 소스가 복잡하게 보일지 모르겠으나 이는 밑수나 지수가 음수이거나 0인 경우의 처리를 위함이다. 구현된 모든 함수의 구현에는 예외상황(예를 들어, 음수의 짝수 제곱근 같은 예외상황) 처리 과정이 있다.

아래의 소스는 대부분 버전의 비쥬얼 스튜디오의 Visual BASIC 컴파일러로 컴파일 되고 실행되게 작성된 소스이다.

소스 첫 부분에

    Private Const MAX_ITER As Integer = 20000
    Private Const M_EPSILON As Double = 1.0e-15

라고 선언하였으니 변수 MAX_ITER 와 M_EPSILON 는 (타입을 갖는) 상수로 선언되었다. Java 언어로는 상수를 선언할 방법이 없지만 Visual BASIC 언어로는 이와 같이 Const 예약어(키워드)를 이용하여 상수를 선언할 수 있다.

예외상황 처리를 위해 예외 던지기 구문 Throw ... 과 예외 받기 구문 Try ... Catch ... End Try 구문을 사용히였다. 그리고 여러 줄을 주석문으로 처리하기 위해 (Visual Basic 구문은 아니고) Visual Basic 컴파일러에게 지시하는 구문이지만

#If False Then
..............................................................
..... 이곳에 여러 줄 주석을 달 수 있음 .......
..............................................................
#End If

를 사용하였다.

 

REM ============================================================================
REM Filename: TestNthRootApp.vb
REM
REM            Approximate square roots, cubic roots and n-th roots of a given number.
REM
REM Compile: vbc TestNthRootApp.vb
REM Execute: TestNthRootApp
REM
REM Date: 2013. 1. 9.
REM Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)
REM ============================================================================

Module ApproximateModule

    Private Const MAX_ITER As Integer = 20000
    Private Const M_EPSILON As Double = 1.0e-15

    Private Const CRLF As String = Chr(13) & Chr(10)

    '
    ' Compute the n-th root of x to a given scale, x > 0.
    '
    Public Function nPow(a As Double, n As Integer) As Double
        Dim y As Double

        If (n > 0) Then
            If (n = 1) Then
                return a
            Else
                If (a = 0.0 Or a = 1.0) Then
                    return a
                ElseIf (a = -1.0) Then
                    If (n Mod 2 = 1) Then
                        return -1.0
                    Else
                        return 1.0
                    End If
                ElseIf (a < 0.0) Then
                    If (n Mod 2 = 1)Then
                        return -nPow(-a, n)
                    Else
                        return nPow(-a, n)
                    End If
                Else
                    y = 1.0
                    For i As Integer = 1 to n
                        y = y * a
                    Next
                    return y
                End If
            End If
        ElseIf (n = 0) Then
            return 1.0
        Else       '  when n < 0
            If (a = 0.0) Then
                Throw New Exception("Negative powering exception of zero.")
            Else
                If (n = -1) Then
                    return 1.0/a
                Else
                    return 1.0/nPow(a, -n)
                End If
            End If
        End If
    End Function

 

    '
    ' Compute the n-th root of x to a given scale, x > 0.
    '
    Public Function gPow(a As Double, n As Integer) As Double
        Dim  y As Double
        Dim r As Double
        Dim one As Integer
        Dim m As Integer

        If (n > 0) Then
            If (n = 1) Then
                return a
            Else
                If (a = 0.0 Or a = 1.0) Then
                    return a
                ElseIf (a = -1.0) Then
                    If (n Mod 2 = 1) Then
                        return -1.0
                    Else
                        return 1.0
                    End If
                ElseIf (a < 0.0) Then
                    If (n Mod 2 = 1) Then
                        return -gPow(-a, n)
                    Else
                        return gPow(-a, n)
                    End If
                Else
                    y = 1.0
                    r = a
                    m = 8*4 - 1           '  8*sizeof(int) - 1;
                    one = 1
                    For i As Integer = 1 To m
                        If ((n And one) = 0) Then
                            y = y * 1.0
                        Else
                            y = y * r
                        End If
                        r = r*r
                        one = one << 1
                        if (one > n) Then
                            Exit For
                        End if
                    Next
                    return y
                End If
            End If
        ElseIf (n = 0) Then
            return 1.0
        Else       '  when n < 0
            If (a = 0.0) Then
                Throw New Exception("Negative powering exception of zero.")
            Else
                if (n = -1) Then
                    return 1.0/a
                Else
                    return 1.0/gPow(a, -n)
                End if
            End If
        End If
    End Function


    '
    ' Compute the n-th root of x to a given scale, x > 0.
    '
    Public Function mPow(a As Double, n As Integer) As Double
        Dim  y As Double
        Dim r As Double
        Dim m As Integer

        If (n > 0) Then
            If (n = 1) Then
                return a
            Else
                If (a = 0.0 Or a = 1.0)  Then
                    return a
                ElseIf (a = -1.0)  Then
                    If (n Mod 2 = 1) Then
                        return -1.0
                    Else
                        return 1.0
                    End If
                ElseIf (a < 0.0) Then
                    If (n Mod 2 = 1) Then
                        return -mPow(-a, n)
                    Else
                        return mPow(-a, n)
                    End If
                Else
                    y = 1.0
                    r = a
                    m = n
                    Do While (m > 0)
                        If ((m And 1) = 1) Then
                            y = y * r
                        End If
                        r = r*r
                        m = m >> 1
                    Loop
                    return y
                End If
            End If
        ElseIf (n = 0) Then
            return 1.0
        Else       '  when n < 0
            If (a = 0.0) Then
                Throw New Exception("Negative powering exception of zero.")
            Else
                If (n = -1) Then
                    return 1.0/a
                Else
                    return 1.0/mPow(a, -n)
                End If
            End If
        End If
    End Function

 

    '
    ' Compute the square root of x to a given scale, x > 0.
    '
    Public Function heronSqrt(a As Double) As Double
        Dim x1 As Double
        Dim x2 As Double
        Dim er As Double
        Dim counter As Integer

        If (a < 0.0) Then
            Throw New Exception("Cannot find the Sqrt of a negative number.")
        ElseIf (a = 0.0 Or a = 1.0) Then
            return a
        Else
            x1 = a
            x2 = (x1 + a/x1)/2.0
            er = x1 - x2
            counter = 0
            Do While (x1 + er <> x1)
                x1 = x2
                x2 = (x1 + a/x1)/2.0
                er = x1 - x2
                If (Math.Abs(er) < Math.Abs(M_EPSILON*x1)) Then
                    Exit Do
                End If
                counter = counter + 1
                If (counter > MAX_ITER) Then
                    Exit Do
                End If
            Loop
            If (counter > MAX_ITER) Then
                Throw New Exception("Inaccurate sqrt exception by too many iterations.")
            End If
            return x2
        End If
    End Function


    '
    ' Compute the cubic root of x to a given scale, x > 0.
    '
    Public Function newtonCbrt(a As Double) As Double
        Dim x1 As Double
        Dim x2 As Double
        Dim er As Double
        Dim counter As Integer

        If (a = 0.0 Or a = 1.0 Or a = -1.0) Then
            return a
        ElseIf (a < 0.0) Then
            return -newtonCbrt(-a)
        Else
            x1 = a
            x2 = (2.0*x1 + a/(x1*x1))/3.0
            er = x1 - x2
            counter = 0
            Do While (x1 + er <> x1)
                x1 = x2
                x2 = (2.0*x1 + a/(x1*x1))/3.0
                er = x1 - x2
                If (Math.Abs(er) < Math.Abs(M_EPSILON*x1)) Then
                    Exit Do
                End if
                counter = counter + 1
                if (counter > MAX_ITER) Then
                    Exit Do
                End if
            Loop
            If (counter >= MAX_ITER) Then
                Throw New Exception("Inaccurate cbrt exception by too many iterations.")
            End If
            return x2
        End If
    End Function


    '
    ' Compute the n-th root of x to a given scale, x > 0.
    '
    Public Function newtonNthRoot(n As integer, a As Double) As Double
        Dim x1 As Double
        Dim x2 As Double
        Dim xn As Double
        Dim er As Double
        Dim counter As Integer

        If (n = 0) Then
            return 1.0
        ElseIf (n = 1) Then
            return a
        ElseIf (n > 0) Then
            If (a = 0.0 Or a = 1.0) Then
                return a
            ElseIf (a = -1.0) Then
                If (n Mod 2 = 1) Then
                    return a
                Else
                    Throw New Exception("Cannot find the even n-th root of a negative number.")
                End If
            ElseIf (a < 0.0) Then
                if (n Mod 2 = 1) Then
                    return -newtonNthRoot(n, -a)
                Else
                    Throw New Exception("Cannot find the even n-th root of a negative number.")
                End If
            ElseIf (a < 1.0) Then
                return 1.0/newtonNthRoot(n, 1.0/a)
            Else
                x1 = a
                xn = mPow(x1, n - 1)
                x2 = ((n - 1)*x1 + a/xn)/n
                er = x1 - x2
                counter = 0
                Do While (x1 + er <> x1)
                    x1 = x2
                    xn = mPow(x1, n - 1)
                    x2 = ((n - 1)*x1 + a/xn)/n
                    er = x1 - x2
                    If (Math.Abs(er) < Math.Abs(M_EPSILON*x1)) Then
                        Exit Do
                    End if
                    counter = counter + 1
                    if (counter > MAX_ITER) Then
                        Exit Do
                    End if
                Loop
                if (counter >= MAX_ITER) Then
                    Throw New Exception("Inaccurate n-th root exception by too many iterations.")
                End If
                return x2
            End If
        Else
            If (a = 0.0) Then
                Throw New Exception("Cannot find the negative n-th root of zero.")
            Else
                return 1.0/newtonNthRoot(-n, a)
            End If
        End If
    End Function


    Sub Main()

        Dim x As Double = 16.0
        Dim u As Double = Math.Sqrt(x)

        Console.WriteLine("[ Testing heronSqrt(double) ]--------------------")
        Console.WriteLine("x = " & x )
        Console.WriteLine("u = Sqrt(" & x & ") = " & u )
        Dim y As Double = heronSqrt(x)
        Console.WriteLine("y = heronSqrt(" & x & ") = " & y )
        Console.WriteLine("y*y = " & y*y )
        Console.WriteLine()

        Console.WriteLine("[ Testing newtonCbrt(double) ]--------------------" )
        x = -216.0
        Console.WriteLine("x = " & x )
        Console.WriteLine("-Exp(Log(-x)/3.0) = " & -Math.Exp(Math.Log(-x)/3.0) )
        Dim w As Double = newtonCbrt(x)
        Console.WriteLine("w = newtonCbrt(" & x & ") = " & w )
        Console.WriteLine("w*w*w = " & w*w*w )
        Console.WriteLine()

        x = 729000000000.0
        Console.WriteLine("x = " & x )
        Console.WriteLine("Exp(Log(x)/3.0) = " & Math.Exp(Math.Log(x)/3.0) )
        w = newtonCbrt(x)
        Console.WriteLine("w = newtonCbrt(" & x & ") = " & w )
        Console.WriteLine("w*w*w = " & w*w*w )
        Console.WriteLine()

        Console.WriteLine("[ Testing newtonNthRoot(int, double) ]--------------------" )
        Dim z As Double = newtonNthRoot(3, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("z = newtonNthRoot(3, " & x & ") = " & z )
        Console.WriteLine("z*z*z = " & z*z*z )
        Console.WriteLine()

        x = 12960000000000000000.0
        z = newtonNthRoot(4, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("z = newtonNthRoot(4, x) = newtonNthRoot(4, " & x & ") = " & z )
        Console.WriteLine("z*z*z*z = " & z*z*z*z )
        Console.WriteLine()

        x = 1.0/12960000000000000000.0
        z = newtonNthRoot(4, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("Exp(Log(x)/4.0) = " & Math.Exp(Math.Log(x)/4.0) )
        Console.WriteLine("z = newtonNthRoot(4, x) = newtonNthRoot(4, " & x & ") = " & z )
        Console.WriteLine("z*z*z*z = " & z*z*z*z )
        Console.WriteLine()


        Try
            x = -4.0
            Console.WriteLine("[ Test Exception heronSqrt(double) ]--------------------" )
            Console.WriteLine("x = " & x )
            Console.WriteLine("Calculating heronSqrt(" & x & ")" )
            y = heronSqrt(x)
            Console.WriteLine("y = heronSqrt(" & x & ") = " & y )
            Console.WriteLine("y*y = " & y*y )
            Console.WriteLine()
        Catch ex As Exception
            Console.WriteLine(ex.Message & CRLF & "Caught some exception in calculating heronSqrt(" & x & ")" )
            Console.WriteLine()
        End Try


        Try
            x = -4.0
            Console.WriteLine("[ Test Exception in newtonCbrt(double) ]--------------------" )
            Console.WriteLine("x = " & x )
            Console.WriteLine("Calculating newtonCbrt(" & x & ")" )
            y = newtonCbrt(x)
            Console.WriteLine("y = newtonCbrt(" & x & ") = " & y )
            Console.WriteLine("y*y*y = " & y*y*y )
            Console.WriteLine()
        Catch ex As Exception
            Console.WriteLine(ex.Message & CRLF & "Caught some exception in calculating newtonCbrt(" & x & ")" )
            Console.WriteLine()
        End Try


        Console.WriteLine("[ Test calculations by powering ]-----------------------------" )
        x = 200.0
        z = newtonNthRoot(10, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("Exp(Log(x)/10.0) = " & Math.Exp(Math.Log(x)/10.0) )
        Console.WriteLine("z = newtonNthRoot(10, x) = newtonNthRoot(10, " & x & ") = " & z )
        Console.WriteLine("Pow(z, 10) = " & Math.Pow(z, 10) )
        Console.WriteLine()

        x = 3001.0
        z = newtonNthRoot(99, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("Exp(Log(x)/99.0) = " & Math.Exp(Math.Log(x)/99.0) )
        Console.WriteLine("z = newtonNthRoot(99, x) = newtonNthRoot(99, " & x & ") = " & z )
        Console.WriteLine("Pow(z, 99) = " & Math.Pow(z, 99) )
        Console.WriteLine()

        x = 3001.0
        z = newtonNthRoot(-99, x)
        Console.WriteLine("x = " & x )
        Console.WriteLine("Exp(Log(x)/-99.0) = " & Math.Exp(Math.Log(x)/-99.0) )
        Console.WriteLine("z = newtonNthRoot(-99, x) = newtonNthRoot(-99, " & x & ") = " & z )
        Console.WriteLine("1.0/Pow(z, 99) = " & 1.0/Math.Pow(z, 99) )
        Console.WriteLine()


        Console.WriteLine("2.1**2.1 = Pow(2.1, 2.1) = "  & Math.Pow(2.1, 2.1) )
        Console.WriteLine("2.1**(-2.1) = Pow(2.1, -2.1) = "  & Math.Pow(2.1, -2.1) )
        Console.WriteLine("2.1**2.1 * 2.1**(-2.1) = Pow(2.1, 2.1) * Pow(2.1, -2.1) = " & Math.Pow(2.1, 2.1)*Math.Pow(2.1, -2.1) )
        Console.WriteLine("2.1**2.1 = Exp(2.1*Log(2.1)) = "  & Math.Exp(2.1*Math.Log(2.1)) )
        Console.WriteLine("2.1**(-2.1) = Exp(-2.1*Log(2.1)) = " & Math.Exp(-2.1*Math.Log(2.1)) )
        Console.WriteLine("2.1**2.1 * 2.1**(-2.1) = Exp(2.1*Log(2.1)) * Exp(-2.1*Log(2.1)) = "  & Math.Exp(2.1*Math.Log(2.1)) * Math.Exp(-2.1*Math.Log(2.1)) )
        Console.WriteLine()


        Dim k As Integer = 301
        x = -1.029
        Dim t1 As Double = nPow(x, k)
        Dim t2 As Double = gPow(x, k)
        Dim t3 As Double = mPow(x, k)
        Console.WriteLine("t1 = nPow(" & x & ", " & k & ") = " & t1 )
        Console.WriteLine("t2 = gPow(" & x & ", " & k & ") = " & t2 )
        Console.WriteLine("t3 = mPow(" & x & ", " & k & ") = " & t3 )
        Console.WriteLine("t1 / t2 = " & (t1 / t2) )
        Console.WriteLine("t1 - t2 = " & (t1 - t2) )
        Console.Write("t1 == t2 ? ")
        If (t1 = t2) Then Console.WriteLine("yes") Else Console.WriteLine("no")
        Console.WriteLine("t1 / t3 = " & (t1 / t3) )
        Console.WriteLine("t1 - t3 = " & (t1 - t3) )
        If (t1 = t3) Then Console.WriteLine("yes") Else Console.WriteLine("no")
        Console.WriteLine("t2 / t3 = " & (t2 / t3) )
        Console.WriteLine("t2 - t3 = " & (t2 - t3) )
        If (t2 = t3) Then Console.WriteLine("yes") Else Console.WriteLine("no")
        Console.WriteLine()

        Console.WriteLine("Done.")
    End Sub

End Module

 

#If False Then
Output:
[ Testing heronSqrt(double) ]--------------------
x = 16
u = Sqrt(16) = 4
y = heronSqrt(16) = 4
y*y = 16

[ Testing newtonCbrt(double) ]--------------------
x = -216
-Exp(Log(-x)/3.0) = -6
w = newtonCbrt(-216) = -6
w*w*w = -216

x = 729000000000
Exp(Log(x)/3.0) = 9000
w = newtonCbrt(729000000000) = 9000
w*w*w = 729000000000

[ Testing newtonNthRoot(int, double) ]--------------------
x = 729000000000
z = newtonNthRoot(3, 729000000000) = 9000
z*z*z = 729000000000

x = 1.296E+19
z = newtonNthRoot(4, x) = newtonNthRoot(4, 1.296E+19) = 60000
z*z*z*z = 1.296E+19

x = 7.71604938271605E-20
Exp(Log(x)/4.0) = 1.66666666666667E-05
z = newtonNthRoot(4, x) = newtonNthRoot(4, 7.71604938271605E-20) = 1.66666666666
667E-05
z*z*z*z = 7.71604938271605E-20

[ Test Exception heronSqrt(double) ]--------------------
x = -4
Calculating heronSqrt(-4)
Cannot find the Sqrt of a negative number.
Caught some exception in calculating heronSqrt(-4)

[ Test Exception in newtonCbrt(double) ]--------------------
x = -4
Calculating newtonCbrt(-4)
y = newtonCbrt(-4) = -1.5874010519682
y*y*y = -4

[ Test calculations by powering ]-----------------------------
x = 200
Exp(Log(x)/10.0) = 1.69864646463425
z = newtonNthRoot(10, x) = newtonNthRoot(10, 200) = 1.69864646463425
Pow(z, 10) = 200

x = 3001
Exp(Log(x)/99.0) = 1.08423618932588
z = newtonNthRoot(99, x) = newtonNthRoot(99, 3001) = 1.08423618932588
Pow(z, 99) = 3001

x = 3001
Exp(Log(x)/-99.0) = 0.922308266265993
z = newtonNthRoot(-99, x) = newtonNthRoot(-99, 3001) = 0.922308266265993
1.0/Pow(z, 99) = 3001.00000000001

2.1**2.1 = Pow(2.1, 2.1) = 4.74963809174224
2.1**(-2.1) = Pow(2.1, -2.1) = 0.210542357266885
2.1**2.1 * 2.1**(-2.1) = Pow(2.1, 2.1) * Pow(2.1, -2.1) = 1
2.1**2.1 = Exp(2.1*Log(2.1)) = 4.74963809174224
2.1**(-2.1) = Exp(-2.1*Log(2.1)) = 0.210542357266885
2.1**2.1 * 2.1**(-2.1) = Exp(2.1*Log(2.1)) * Exp(-2.1*Log(2.1)) = 1

t1 = nPow(-1.029, 301) = -5457.92801577163
t2 = gPow(-1.029, 301) = -5457.92801577169
t3 = mPow(-1.029, 301) = -5457.92801577169
t1 / t2 = 0.999999999999989
t1 - t2 = 6.18456397205591E-11
t1 == t2 ? no
t1 / t3 = 0.999999999999989
t1 - t3 = 6.18456397205591E-11
no
t2 / t3 = 1
t2 - t3 = 0
yes

Done.
#End If

 

 

Posted by Scripter
,

역삼각함수란 삼각함수의 역함수를 의미하고,

역쌍곡선함수란 쌍곡선함수의 역함수를 의미한다.

수학에서 sin 함수의 역함수는 arcsin 으로 표기되는데,

FreeBASIC 언어에서는 asin 함수로 구현되어 있다.

아래의 소스는 FreeBASIC 의 (명령줄 컴파일 명령) fbc 로 컴파일되는 소스이다.

참고 1. FreeBASIC 은 이전(MS-DOS 시절)에 쓰던 Quick BASIC 과 유사하며, Quick BASIC을 발전시킨 것이라고 보변 된다. 아래는 Wikipedia 에서 적어 놓은 FreeBASIC 의 설명이다.

---------------------------------------------------

FreeBASIC is a free/open source (GPL), 32-bit BASIC compiler[2] for Microsoft Windows, protected-mode DOS (DOS extender), Linux, FreeBSD and Xbox.

---------------------------------------------------

 

참고 2.  Double 타입의 부동소수점수를 원하는 위치에서 적당히 반올림하여 출력하기 위해서는 Format 또는 Format$ 함수를 써야 하는데, 이를 위해서는 FreeBASIC 언어에서는 소스에

#include "string.bi"

를 추가해야 한다.

(참고로, FreeBASIC 언어에서는 Print Using 과 "#.#########" 포맷을 이용해서 Double 타입을 출력하면, 근사값이라는 의미로 수치 앞에 퍼센트 기호(%)가 붙는다.)

 

참고 3.  제곱근을 구하기 위해 C, Java, Ruby, Python 언어에서는 sqrt 함수를 사용하고, Visual BASIC, C# 언어에서는 Sqrt 함수를 사용하지만, FreeVASIC 언어에서는 Quick BASIC 언어에서 처럼 Sqr 로 구현되어 있다. (Sqrt 가 아니라 마지막 분자 t 가 빠진 Sqr 임에 주의한다.)

 

참고 4.  FreeBASIC 언어에는 쌍곡선 함수가 구현되어 있지 않아 아래의 소스에 FreeBASIC 지수함수 Exp 를 이용하여 쌍곡ㅅ선 함수  sinh 함수와 cosh 함수를 구현헤 놓았다. 

 

REM =============================================================
REM Filename: testArcSine.bas
REM
REM    This source should be compiled by using FreeBASIC,
REM    which can be downloaded from http://www.freebasic.net
REM
REM Compile: fbc testArcSine.bas
REM Execute: testArcSine
REM
REM Date: 2013. 1. 2.
REM Copyright (c) pkim _AT_ scripts.pe.kr
REM =============================================================

#include "string.bi"

Function asinh(x As Double) As Double
        Dim y As Double = log(x + Sqr(x*x + 1))
        return y
End Function

Function cosh(x As Double) As Double
        Dim y As Double = (Exp(x) + Exp(-x))/2.0
        return y
End Function

Function sinh(x As Double) As Double
        Dim y As Double = (Exp(x) - Exp(-x))/2.0
        return y
End Function

Function acosh(x As Double) As Double
        Dim y As Double = log(x + Sqr(x*x - 1))
        return y
End Function


Sub Main()
        Dim x As Double = -0.9
        Dim y As Double = asin(x)
        ' Print Using "y = asin(" & x & ") = #"; y
        ' Print Using "y = asin(" & x & ") = #.#########"; y
        Print "y = asin(" & x & ") = "& Format$(y, "0.#########")
        ' Print "sin(y) = sin(" & y & ") = " & sin(y)
        ' Print Using "sin(y) = sin(#.########) = #"; y, sin(y)
        Print "sin(y) = sin(" & Format$(y, "0.#########") & ") = " & sin(y)
        Print

        x = 1.1
        Dim u As Double = acosh(x)
        ' Print "u = acosh(" & x & ") = " & u
        Print "u = acosh(" & x & ") = " & Format$(u, "0.#########")

        Dim v As Double = asinh(x)
        ' Print "v = asinh(" & x & ") = " & v
        Print "v = asinh(" & x & ") = " &  Format$(v, "0.##########")

        ' Print "cosh(u) = cosh(" & u & ") = " & Cosh(u)
        ' Print "sinh(v) = sinh(" & v & ") = " & Sinh(v)
        Print "cosh(u) = cosh(" & Format$(u, "0.#########") & ") = " & Cosh(u)
        Print "sinh(v) = sinh(" & Format$(v, "0.#########") & ") = " & Sinh(v)
           
        ' Print Format$(1.23, "#.#")
End Sub


Main()

' ---------------------------
' Output:
' y = asin(-0.9) = -1.119769515
' sin(y) = sin(-1.119769515) = -0.9
'
' u = acosh(1.1) = 0.4435682544
' v = asinh(1.1) = 0.9503469298
' cosh(u) = cosh(0.4435682544) = 1.1
' sinh(v) = sinh(0.9503469298) = 1.1
' ---------------------------

 

 

 

Posted by Scripter
,

다음은 세 개의 Public 클래스로 구성되어 있다. 각 클래스는 별도의 파일로 저장되어야 한다.
이 예제는 C#용으로 제공된 클래스 상속 예제와의 비교를 위해 제공된다.
(Java와는 달리) 하나의 Visual Basic 소스파일에 public 클래스가 여러 개 존재해도 된다. 소스파일명도 Public 클래스명과 달라도 된다. (비스크립트형) Visual Basic 언어는 소스 코드에서 C, C++, C#, Java  언어 처럼 대소문자 구별을 엄격히 한다.

Parent는 부모 클래스이고 Child는 Parent에서 상속 받은 자식 클래스이다.


컴파일하는 명령은 

     vbc TestSubclassing.bas Parent.bas Child.bas

이다.

' Filename: Parent.bas

Imports System

Namespace MyTestApplication1

    Public Class Parent

        Private name As String

        Public Sub New()
        End Sub

        Public Sub New(ByVal name AS String)
            Me.name =  name
        End Sub

        Public Sub SayName()
            Console.WriteLine("I am a parent, {0}", name)
        End Sub
    End Class
End Namespace




 

' Filename: Child.bas

Imports System

Namespace MyTestApplication1

    Public Class Child
                 Inherits Parent

        Private name As String

        Public Sub New(ByVal name As String)
            ' MyBase.New(name)               ' 클래스 상속시 부모 클래스 생성자 호출
            Me.name =  name
        End Sub

        Public Overloads Sub SayName()
            Console.WriteLine("I am a child, {0}", name)
        End Sub
    End Class
End Namespace




 

' Filename: TestSubclassing.bas
'
' See: http://www.gosu.net/GosuWeb/ArticleMSView.aspx?ArticleCode=1021

Imports System

Namespace MyTestApplication1

    Public Class TestSubclassing
        Public Shared Sub Main(args() As String)
            Dim obj As Child = New Child("Dooly")
            obj.SayName()
        End Sub
    End Class
End Namespace



실행> TestSubclassing
I am a child, named as Dooly


크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  TestStringFindInList.bas]------------------------------------------------
Imports System
Imports System.Collections
Imports System.Collections.Generic

Namespace MyTestApplication1

    Public Class TestStringFindInList

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args As String())
            'Dim words As New List(Of String) From { "하나", "둘", "셋", "넷", "다섯", "여섯" }
            Dim words As New List(Of String)
            words.Add("하나")
            words.Add("둘")
            words.Add("셋")
            words.Add("넷")
            words.Add("다섯")
            words.Add("여섯")
            Dim where As Integer

            Console.Write("list: ")
            PrintList(words)

            where = Find(words, "셋")
            If where > 0 Then
                Console.Write("발견!  ")
                Console.WriteLine("Next word of 셋 in list: " & words(where+1))
            End If

            Console.WriteLine("Sorting...")
            words.Sort()

            Console.Write("list: ")
            PrintList(words)

            where = Find(words, "셋")
            If where > 0 Then
                Console.Write("발견!  ")
                Console.WriteLine("Next word of 셋 in list: " & words(where+1))
            End If
        End Sub

        Shared Function Find(arr as List(Of String), s as String ) as Integer
            For i = 0 To arr.Count - 1
                If arr(i).IndexOf(s) >= 0 Then
                    Return i
                End If
            Next
            Return -1
        End Function

        Shared Sub PrintList(arr As List(Of String))
            Dim i As Integer
            Console.Write("[")
            For i = 0 To arr.Count - 2
                Console.Write("{0}, ", arr(i))
            Next i
            If arr.Count > 0 Then
                Console.Write("{0}", arr(arr.Count - 1))
            End If
            Console.WriteLine("]")
        End Sub
    End Class
End Namespace
------------------------------------------------


컴파일> vbc testStringFindInList.bas

실행> TestStringFindInList
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯


크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,


[파일명:  TestStringFindApp.bas]------------------------------------------------
Imports System
Imports System.Collections
Imports System.Collections.Generic

Namespace MyTestApplication1

    Public Class TestStringFindApp

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args As String())
            Dim words() As String = { "하나", "둘", "셋", "넷", "다섯", "여섯" }
            Dim where As Integer

            Console.Write("array: ")
            PrintArray(words)

            where = Find(words, "셋")
            If where > 0 Then
                Console.Write("발견!  ")
                Console.WriteLine("Next word of 셋 in array: " & words(where+1))
            End If

            Console.WriteLine("Sorting...")
            Array.Sort(words)

            Console.Write("array: ")
            PrintArray(words)

            where = Find(words, "셋")
            If where > 0 Then
                Console.Write("발견!  ")
                Console.WriteLine("Next word of 셋 in array: " & words(where+1))
            End If
        End Sub

        Shared Function Find(arr() as String, s as String ) as Integer
            For i = 0 To arr.Length - 1
                If arr(i).IndexOf(s) >= 0 Then
                    Return i
                End If
            Next
            Return -1
        End Function

        Shared Sub PrintArray(arr As Object())
            Dim i As Integer
            Console.Write("[")
            For i = 1 To arr.Length - 2
                Console.Write("{0}, ", arr(i))
            Next i
            If arr.Length > 0 Then
                Console.Write("{0}", arr(arr.Length - 1))
            End If
            Console.WriteLine("]")
        End Sub
    End Class
End Namespace
------------------------------------------------


컴파일> vbc testStringFindApp.bas

실행> TestStringFindApp
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,

[파일명:  TestSortApp.bas]------------------------------------------------
Imports System
Imports System.Collections
Imports System.Collections.Generic

Namespace MyTestApplication1

    Public Class TestSortApp

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args As String())
            Dim arr(args.Length) As String
            Dim i As Integer
            For i = 0 To args.Length - 1
                arr(i) = args(i)
            Next i
            Array.Sort(arr)
            PrintArray(arr)
        End Sub

        Shared Sub PrintArray(arr As Object())
            Dim i As Integer
            Console.Write("[")
            For i = 1 To arr.Length - 2
                Console.Write("{0}, ", arr(i))
            Next i
            If arr.Length > 0 Then
                Console.Write("{0}", arr(arr.Length - 1))
            End If
            Console.WriteLine("]")
        End Sub
    End Class
End Namespace
------------------------------------------------


컴파일> vbc TestSortApp.bas

실행> TestSortApp one two three four five
[five, four, one, three, two]

실행> TestSortApp 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]


 

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,


초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 C# 소스이다.

' --------------------------------------------
'  Filename: MakeMultTableVB.bas
'
'     Print a multiplication table.
'
'     Compile: vbc MakeMultTableVB.bas
'     Execute: MakeMultTableVB 230 5100
'
'  Date: 2009/03/07
'  Author: pkim (AT) scripts.pe.kr
' --------------------------------------------

Imports System

Namespace MyTestApplication1

    Class MakeMultTableApp

        Shared Sub PrintUsing()
            Console.WriteLine("Using: MakeMultTableApp [number1] [number2]")
            Console.WriteLine("Print a multiplication table for the given two integers.")
        End Sub

        Shared Sub PrintMultTable(x As long, y As long)
            DIM nx As long = x
            DIM ny As long = y
            If nx < 0 Then nx = - nx
            If ny < 0 Then ny = - ny
            DIM ntail1 As int32 = 0
            DIM ntail2 As int32 = 0
            While nx Mod 10 = 0
                nx = Convert.ToInt64(Math.Floor(nx / 10))
                ntail1 = ntail1 + 1
            End While
            While ny MOD 10 = 0
                ny = Convert.ToInt64(Math.Floor(ny / 10))
                ntail2 = ntail2 + 1
            End While
            Dim z As long = nx * ny
            Dim strZ As String = "" & z
            Dim strX As String = "" & nx
            Dim strY As String = "" & ny
            Dim n As Integer = Len(strY)
            Dim zeros As String  = "0000000000000000000000000000000000000000"
            Dim whites As String = "                                        "
            Dim bars As String   = "----------------------------------------"
            Dim line1 As String, line2 As String, line3 As String, line4 As String
            Dim loffset As String = "       "
            line4 = loffset & strZ
            line1 = loffset & Mid(whites, 1, Len(strZ) - Len(strX)) & strX
            line2 = "   x ) " &  Mid(whites, 1, Len(strZ) - Len(strY)) & strY
            line3 = "     --" &  Mid(bars, 1, Len(strZ))
            Console.WriteLine(line1 & Mid(zeros, 1, ntail1))
            Console.WriteLine(line2 & Mid(zeros, 1, ntail2))
            Console.WriteLine(line3)
            If Len(strY) > 1 Then
                Dim y1 As Integer
                Dim strT As String
                For i As Integer = 0 To Len(strY) - 1
                    y1 = Convert.ToInt32(Mid(strY, Len(strY) - i, 1))
                    If y1 <> 0 Then
                        strT = "" & (nx * y1)
                        Console.WriteLine(loffset & Mid(whites, 1, Len(strZ) - Len(strT) - i) & strT)
                    End If
                Next
                Console.WriteLine(line3)
            End If
            Console.WriteLine(line4 & Mid(zeros, 1, ntail1) & Mid(zeros, 1, ntail2))
        End Sub

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args() As String)
            DIM x As long, y As long
            If args.Length >= 2 Then
                x = Convert.ToInt64(args(0))
                y = Convert.ToInt64(args(1))
                Console.WriteLine("")
                PrintMultTable(x, y)
            Else
                PrintUsing()
            End If
        End Sub
    End Class
End Namespace




컴파일> vbc MakeMultTableVB.bas
실행> MakeMultTableVB 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,

다음은 초등학교에서 배우는 나눗셈 계산표를 만들어주는 Visual Basic 소스 코드이다.
나눗셈 계산표를 완성하고 나서 약수, 배수 관계를 알려준다.

C# 코드로 작성된 BigInteger.cs 와 함께 컴파일하여 실행시키면 된다.

'  Filename: MakeDivisionTableApp.bas
'
'  Purpose:  Make a division table in a handy written form.
'
'  Compile: csc /target:module BigInteger.cs
'           vbc MakeDivisionTableApp.bas /addmodule:BigInteger.netmodule
'  Execute: MakeDivisionTableApp 12345 32
'           MakeDivisionTableApp 500210 61
'
'     Date:  2009/02/14
'   Author:  PH Kim   [ pkim ((AT)) scripts.pe.kr ]

Imports System
Imports ScottGarland        ' for C# 2.0   Get at http://www.codeplex.com/biginteger/Release/ProjectReleases.aspx?ReleaseId=16762
 
Namespace MyTestApplication1

    Class MakeDivisionTableApp

        Shared Dim ZERO As BigInteger = New BigInteger("0")
       
        Shared Sub printUsage()
             ' Console.WriteLine("Using: MakeDivisionTableApp [numerator] [denominator]")
             ' Console.WriteLine("Make a division table in a handy written form.")
             Console.WriteLine("사용법: MakeDivisionTableApp [피제수] [제수]")
             Console.WriteLine("손으로 작성한 형태의 나눗셈 표를 만들어준다.")
        End Sub

        Shared Function simplify(v As Double) As String
            Dim t As String = "" & Convert.ToString(v)
            If t.EndsWith(".0") Then
                t = Mid(t, 1, t.Length - 2)
            End If
            simplify = t
        End Function

        Shared Function simplify(v As BigInteger, width As Integer) As String
            Dim t As String = "" & Convert.ToString(v)
            If t.EndsWith(".0") Then
                t = Mid(t, 1, t.Length - 2)
            End If
            Dim len As Integer = t.Length
            If len < width Then
                t = Mid("                                                                                             ", 1, width - len) & t
            End If
            simplify = t
        End Function

        Function getSuffix(v As BigInteger) As String
            Dim t As BigInteger = BigInteger.Modulus(v, New BigInteger("10"))
            Dim suffix As String = "은"
            If "2459".IndexOf("" & Convert.ToString(t)) >= 0 Then
                suffix = "는"
            End If
            getSuffix = suffix
        End Function

        Function makeTable(numer As BigInteger, denom As BigInteger, quotient As BigInteger) As BigInteger
            Dim strNumer As String = "" & Convert.ToString(numer)
            Dim  strDenom As String = "" & Convert.ToString(denom)
            Dim  strQuotient As String = "" & Convert.ToString(quotient)
            DIm lenN As Integer = strNumer.Length
            DIm lenD As Integer = strDenom.Length
            DIm lenQ As Integer = strQuotient.Length
            DIm offsetLeft As Integer = 3 + lenD + 3
            DIm spaces As String = "                                                                                 "
            DIm uline  As String = Mid("_________________________________________________________________________________", 1, lenN + 2)
            DIm sline  As String = Mid("---------------------------------------------------------------------------------", 1, lenN)
            DIm bias As Integer = lenN - lenQ

            Console.WriteLine(Mid(spaces, 1, offsetLeft) & Mid(spaces, 1, bias) & Convert.ToString(quotient))
            Console.WriteLine(Mid(spaces, 1, offsetLeft - 2) & uline)
            Console.Write("   " & strDenom & " ) " & strNumer)
            Dim strTmpR As String = Mid(strNumer, 1, bias + 1)
            Dim tmpR As BigInteger = New BigInteger(strTmpR)
            Dim tmpSub As BigInteger = ZERO
            Dim oneDigit As String = Nothing

            For i As Integer = 0 To lenQ - 1
                If Mid(strQuotient, i + 1, 1) = "0" Then
                    If i + 1 < lenQ Then
                        oneDigit = Mid(strNumer, bias + i + 1 + 1, 1)
                        Console.Write(oneDigit)
                        strTmpR = strTmpR & oneDigit
                        tmpR = New BigInteger(strTmpR)
                    End If
                Else
                    Console.WriteLine()
                    tmpSub = BigInteger.Multiply(New BigInteger(Mid(strQuotient, i + 1, 1)), denom)
                    Console.WriteLine(Mid(spaces, 1, offsetLeft) & simplify(tmpSub, bias + i + 1))
                    Console.WriteLine(Mid(spaces, 1, offsetLeft) & sline)
                    tmpR = BigInteger.Subtract(tmpR, tmpSub)
                    If tmpR.Equals(ZERO) And i + 1 < lenQ Then
                        Console.Write(Mid(spaces, 1, offsetLeft) & Mid(spaces, 1, bias + i + 1))
                    Else
                        Console.Write(Mid(spaces, 1, offsetLeft) & simplify(tmpR, bias + i + 1))
                    End If

                    strTmpR = "" & Convert.ToString(tmpR)
                    If i + 1 < lenQ Then
                        oneDigit = Mid(strNumer, bias + i + 1 + 1, 1)
                        Console.Write(oneDigit)
                        strTmpR = strTmpR & oneDigit
                        tmpR = New BigInteger(strTmpR)
                    End If
                End If
            Next

            Console.WriteLine()
            makeTable = tmpR
        End Function

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args() As String)
            If args.Length < 2 Then
                printUsage()
                Environment.Exit(1)
            End If

            Dim a As BigInteger = Nothing
            Dim b As BigInteger = Nothing

            Try
                a = New BigInteger(args(0))
                b = New BigInteger(args(1))
            Catch ex As ArgumentOutOfRangeException
                Console.WriteLine(ex)
                Console.WriteLine("피제수: " & args(0) & ", 제수: " & args(1))
                Console.WriteLine("숫자 입력에 오류가 있습니다.")
                Environment.Exit(1)
            Catch ex As ArgumentNullException
                Console.WriteLine(ex)
            Catch ex As FormatException
                Console.WriteLine(ex)
                Console.WriteLine("피제수: " & args(0) & ", 제수: " & args(1))
                Console.WriteLine("숫자 입력에 오류가 있습니다.")
                Environment.Exit(1)
            End Try

            If BigInteger.Compare(a, ZERO) <= 0 Then
                Console.WriteLine("피제수: " & Convert.ToString(a))
                Console.WriteLine("피제수는 양의 정수라야 합니다.")
                Environment.Exit(1)
            ElseIf BigInteger.Compare(b, ZERO) <= 0 Then
                Console.WriteLine("제수: " & Convert.ToString(b))
                Console.WriteLine("제수는 양의 정수라야 합니다.")
                Environment.Exit(1)
            End If

            Dim app As MakeDivisionTableApp = New MakeDivisionTableApp()
            Dim q As BigInteger = BigInteger.Divide(a, b)
            Dim r As BigInteger = BigInteger.Modulus(a, b)
            Console.Write("나눗셈 " & Convert.ToString(a) & " ÷ " & Convert.ToString(b) & " 의 결과: ")
            Console.Write("몫: " & Convert.ToString(q) & ", ")
            Console.WriteLine("나머지: " & Convert.ToString(r))
            Console.WriteLine()

            Dim k As BigInteger = app.makeTable(a, b, q)
            Console.WriteLine()

            If k.Equals(r) Then
                Console.WriteLine("나머지: " & Convert.ToString(k))
            End If

            If k.Equals(ZERO) Then
                Console.WriteLine(Convert.ToString(a) & " = " & Convert.ToString(b) & " x " & Convert.ToString(q))
                Console.WriteLine(Convert.ToString(a) & app.getSuffix(a) & " " & Convert.ToString(b) & "의 배수(mupltiple)이다.")
                Console.WriteLine(Convert.ToString(b) & app.getSuffix(b) & " " & Convert.ToString(a) & "의 약수(divisor)이다.")
            Else
                Console.WriteLine(Convert.ToString(a) & " = " & Convert.ToString(b) & " x " & Convert.ToString(q) & " + " & Convert.ToString(r))
                Console.WriteLine(Convert.ToString(a) & app.getSuffix(a) & " " & Convert.ToString(b) & "의 배수(mupltiple)가 아니다.")
            End If
        End Sub
    End Class
End Namespace




컴파일> csc /target:module BigInteger.cs
컴파일> vbc MakeDivisionTableApp.bas /addmodule:BigInteger.netmodule

실행> MakeDivisionTableApp 500210 61

나눗셈 500210 ÷ 61 의 결과: 몫: 8200, 나머지: 10

          8200
      ________
   61 ) 500210
        488
        ------
         122
         122
        ------
            10

나머지: 10
500210 = 61 x 8200 + 10
500210은 61의 배수(mupltiple)가 아니다.




크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Visual Basic 소스 코드이다.

메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 

         Shared Function ConvertAtoI(s As String, radix As Integer) As Int64
         Shared Function ConvertItoA(num As Int64, int radix As Integer) As String

의 구현과 이용이다. 지원되는 진법은 2진법부터 36진법까지이다.
Visual Basic에는 Java의 StrinngTokener가 구현되어 있지 않다.
그래서 Java의 StrinngTokener와 비슷한 Visual Basic용 StrinngTokener.Token이라는
클래스를 구현해 보았다.

'  Filename: ConvertRadixApp.bas
'            Convert radix in a interactive mode.
'
'  Compile: vbc ConvertRadixApp.bas
'  Execute: ConvertRadixApp
'
'      Date:  2009/02/15
'    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

Imports System

Namespace StringTokenizer

    Class Token
        Private Dim data As String
        Private Dim delimeter As String
        Private Dim tokens() As String
        Private Dim index As Integer
 
 
        Public Sub New(strdata As String)
            Init(strdata, " ")
        End Sub

        Public Sub New(strdata As String, delim As String)
            Init(strdata, delim)
        End Sub

        Sub Init(strdata As String, delim As String)
            data = strdata
            delimeter = delim
            Dim data2 As String = ""
            Dim isDelim As Boolean = False
            Dim c As String
            For i As Integer = 0 To data.Length - 1
             c = Mid(data, i + 1, 1)
             If delim.Contains(c) Then
                 If Not isDelim Then
                     isDelim = True
           data2 = data2 & c
                 End If
                 Continue For
             End If
         data2 = data2 & c
            Next
            tokens = data2.Split(delimeter.ToCharArray())
            index = 0
        End Sub

        Public Function Count() As Integer
            Count = tokens.Length
        End Function

        Public Function HasMoreTokens() As Boolean
            HasMoreTokens = index < tokens.Length
        End Function

        Public Function NextToken() As String
            If index < tokens.Length Then
                index = index + 1
                NextToken = tokens(index - 1)
                return tokens(index - 1)
            Else
                NextToken = ""
                return ""
            End If
        End Function
    End Class
End Namespace

Namespace MyTestApplication1

    Class ConvertRadixApp

        Shared Sub PrintUsage()
            Console.WriteLine("Usage: ConvertRadixApp")
            Console.WriteLine("Convert radix in a interactive mode, where the maximum radix is 36.")
        End Sub

        Sub PrintAbout()
            Console.WriteLine("    About: Convert radix in a interactive mode.")
        End Sub

        Sub PrintMainMenu()
            Console.WriteLine("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
        End Sub

        Sub PrintMainPrompt()
            Console.Write("  Prompt> ")
        End Sub

        Sub PrintSubMenu(srcRadix As Integer, destRadix As Integer)
            Console.WriteLine("    Convert Radix_" & srcRadix & " to Radix_" & destRadix)
            Console.WriteLine("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
        End Sub

        Sub PrintSubPrompt()
            Console.Write("    Input Value>> ")
        End Sub

        Shared BASE36 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

        Shared Function ConvertItoA(num As Int64, radix As Int32) As String
            Dim tmp As String
            Dim ret As String
            Dim arr As String
            Dim q As Int64
            Dim r As Int64
            Dim isNegative As Boolean = False
            If num < 0L Then
                isNegative = True
                num = -num
            End If
            arr = ""
            q = num
            r = 0L

            While q >= Convert.ToInt64(radix)
                r = q Mod Convert.ToInt64(radix)
                q = Convert.ToInt64(Math.Floor(q / Convert.ToInt64(radix)))
                tmp = Mid(BASE36, Convert.ToInt32(r) + 1, 1)
                arr = arr & tmp
            End While
            tmp = Mid(BASE36, Convert.ToInt32(q) + 1, 1)
            arr = arr & tmp
            If isNegative Then
                arr = arr & "-"
            End If

            ret = ""
            For j As Integer = 0 To arr.Length - 1
               ret = ret & Mid(arr, arr.Length - j - 1 + 1, 1)
            Next
            ConvertItoA = ret
        End Function

        Shared Function ConvertAtoI(s As String, radix As Integer) As Int64
            Dim ret As Int64 = 0L
            Dim isNegative As Boolean = False
            Dim len As Integer = s.Length
            Dim c As char
            Dim i As Integer
            Dim val As Int64 = 0L

            c = s(0)
            If c = "-"c Then
                isNegative = True
            ElseIf c >= "0"c And c <= "9"c Then
                ret = Convert.ToInt64(c) - Convert.ToInt64("0"c)
            ElseIf c >= "A"c And c <= "Z"c Then
                ret = Convert.ToInt64(c) - Convert.ToInt64("A"c) + 10L
            ElseIf c >= "a"c And c <= "z"c Then
                ret = Convert.ToInt64(c) - Convert.ToInt64("a"c) + 10L
            End If
            If (ret >= Convert.ToInt64(radix)) Then
                Console.WriteLine("        Invalid character!")
                ConvertAtoI = ret
               Return ret
            End If

            For i = 1 To len - 1
                c = s(i)
                ret = ret * radix
                If c >= "0"c And c <= "9"c Then
                    val = Convert.ToInt64(c) - Convert.ToInt64("0"c)
                ElseIf c >= "A"c And c <= "Z"c Then
                    val = Convert.ToInt64(c) - Convert.ToInt64("A"c) + 10L
                ElseIf c >= "a"c And c <= "z"c Then
                    val = Convert.ToInt64(c) - Convert.ToInt64("a"c) + 10L
                End If
                If (val >= Convert.ToInt64(radix)) Then
                    Console.WriteLine("        Invalid character!")
                    ConvertAtoI = ret
                   Return ret
                End If
                ret = ret + val
            Next

            If isNegative Then
             ret = -ret
            End If
            ConvertAtoI = ret
            return ret
        End Function

        Function ConvertRadix(s As String, srcRdx As Integer, destRdx As Integer) As String
            Dim val As Int64
            Dim ret As String = ""
            Try
                val = ConvertAtoI(s, srcRdx)
                         ' Console.WriteLine("val = " + val);
                ret = ConvertItoA(val, destRdx)
                ConvertRadix = ret.ToUpper()
                return ret.ToUpper()
            Catch nfx As Exception
                ' Console.WriteLine("    Error: " + nfx.getMessage() + " cantains some invalid character.");
                Console.Write("    Error: ")
                Console.Write(nfx)
                Console.WriteLine(" cantains some invalid character.")
                ret = "????"
                ConvertRadix = ret.ToUpper()
                return ret.ToUpper()
            End Try
        End Function

        Sub  DoConvert(srcRadix As Integer, destRadix As Integer)
            Dim cmd As String
            Dim srcStr As String = ""
            Dim destStr As String = ""
            Console.WriteLine()
            PrintSubMenu(srcRadix, destRadix)
            Try
                Do
                    PrintSubPrompt()
                    cmd = Console.ReadLine()
                    If "main()" = cmd Then
                        return
                    ElseIf "exit()" = cmd Or "quit()" = cmd Then
                        Environment.Exit(0)
                    End If

                    Try
                        Convert.ToInt32(cmd, srcRadix)
                        srcStr = cmd
                        destStr = ConvertRadix(srcStr, srcRadix, destRadix)
                        Console.WriteLine("        ( " & srcStr & " )_" & srcRadix &  "   --->   ( " & destStr & " )_" & destRadix)
                        Console.WriteLine()
                    Catch ex As FormatException
                         Console.Write(cmd + ": ")
                         Console.WriteLine(ex)
                    End Try
                Loop
            Catch ex As Exception
                Console.WriteLine(ex)
            End Try
        End Sub

        Sub DoStart()
            Dim sep() As Char = New Char() { " "c, ","c, Chr(9) }   ' Chr(9) = Tab = \t
            Dim line As String
            Dim cmd As String
            Dim srcRadix As Integer = 10
            Dim destRadix As Integer = 10
            Dim onlyOnce As Boolean = True
            Try
                Do
                    Console.WriteLine()
                    If onlyOnce Then
                        Console.WriteLine("  The supported maximum radix is 36.")
                        onlyOnce = False
                    End If
                    PrintMainMenu()
                    PrintMainPrompt()
                    cmd = Console.ReadLine()
                    If "qQxX".Contains(cmd) And cmd.Length = 1 Then
                        Environment.Exit(0)
                    ElseIf "aA".Contains(cmd) And cmd.Length = 1 Then
                        PrintAbout()
                    ElseIf "sS".Contains(cmd) And cmd.Length = 1 Then
                        Console.Write("  Input the source and target radices (say, 16 2): ")
                        line = Console.ReadLine()
                        Dim tok As StringTokenizer.Token = New StringTokenizer.Token(line, " , \t")
                        While tok.Count() <> 2
                            Console.Write("  Input the source and target radices (say, 16 2): ")
                            line = Console.ReadLine()
                            tok = New StringTokenizer.Token(line, " , \t")
                        End While

                        Try
                            srcRadix = Convert.ToInt32(tok.NextToken())
                            destRadix = Convert.ToInt32(tok.NextToken())
                            DoConvert(srcRadix, destRadix)
                        Catch ex As FormatException
                            Console.WriteLine(ex)
                        End Try
                    End If
                Loop
            Catch ex As Exception
                Console.WriteLine(ex)
            End Try
        End Sub

        ' Java 언어의 main 메소드에 해당하는 Visual Basic의 Main
        Shared Sub Main(ByVal args() As String)
            If args.Length = 0 Then
                 '
            ElseIf args.Length > 0 And "-h" = args(0) Then
                PrintUsage()
                Environment.Exit(1)
            End If
            Dim app As ConvertRadixApp = New ConvertRadixApp()
            app.DoStart()
        End Sub
    End Class
End Namespace




컴파일> vbc ConvertRadixApp.bas

실행> ConvertRadixApp

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 16

    Convert Radix_10 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 256
        ( 256 )_10   --->   ( 100 )_16

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 10

    Convert Radix_16 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> FFFF
        ( FFFF )_16   --->   ( 65535 )_10

    Input Value>> exit()


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,