error in the final result of extended euclidean code - vb.net

this application for computing the gcd by using extended euclidean but it give me just the value for first iteration but i need the final values of x2 y2 a
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x1 As Integer
Dim x2 As Integer
Dim y1 As Integer
Dim y2 As Integer
Dim x As Integer
Dim y As Integer
Dim a As Integer
Dim temp As Integer
a = CInt(TextBox1.Text)
Dim b As Integer
b = CInt(TextBox2.Text)
Dim q As Integer
x1 = 0
y1 = 1
x2 = 1
y2 = 0
If b > a Then
temp = a
a = b
b = temp
End If
Do While (b <> 0)
q = Math.Floor(a / b)
a = b
b = a Mod b
x = x2 - q * x1
x2 = x1
y = y2 - q * y1
y2 = y1
x1 = x
y1 = y
Loop
MessageBox.Show("the final value of x2 is " & CStr(x2) & "the final value of y2 is " & CStr(y2) & "the GCD is " & CStr(a), " the result ")
End Sub

Here's your problem:
a = b
b = a Mod b
In the second statement, a is already equal to b, so a Mod b is always zero.

'Euclid's algorithm
'code assumes that you are looking for the GCD of the
'values entered into TextBox1 and TextBox2
Dim dividend As Long
Dim divisor As Long
Dim quotient As Long
Dim remainder As Long
If Long.TryParse(TextBox1.Text, dividend) Then
If Long.TryParse(TextBox2.Text, divisor) Then
'place in correct order
quotient = Math.Max(dividend, divisor) 'determine max number
remainder = Math.Min(dividend, divisor) 'determine min number
dividend = quotient 'max is dividend
divisor = remainder 'min is divisor
Do
quotient = Math.DivRem(dividend, divisor, remainder) 'do the division
'set up for next divide
dividend = divisor 'dividend is previous divisor. if remainder is zero then dividend = GCD
divisor = remainder 'divisor is previous remainder
Loop While remainder <> 0 'loop until the remainder is zero
Label1.Text = dividend.ToString("n0")
End If
End If

Related

Graphics drawline scaling vb.net

I'm trying to develop a program that has been made by another person.
What I develop is just for showing the measurement point like the picture below.
There are min and max data that appear in the form and it's showing from the smallest to the largest value and every time the mouse moves from left to right, the measuring point value will adjust to the graph value that has been determined as above.
The problem is data accuracy at the measuring point does not match with the value that has been determined, this is because the graphic is out of frame.
Here is the code for showing graphics;
Private Sub UpdateDiaGraph()
Call Me.ClearGraph(Me.gDia, Me.PicDiaGraph)
Call Me.InitializeGraph(Me.gDia, Me.PicDiaGraph, Me.recDia)
If Me.dsData.Tables("Dia").Rows.Count = 0 Then
Exit Sub
End If
Dim drs() As DataRow = Me.dsData.Tables("Dia").Select("", "[PathNo],[EquipmentNo],[Point]")
Dim pathNo As Integer = 0
Dim equipmentNo As Integer = 0
Dim diaCount As Integer = 0
Dim maxPoint As Integer = 0
Dim longestDiaCount As Integer = 0
Dim upper As New List(Of Decimal)
Dim lower As New List(Of Decimal)
For Each dr As DataRow In drs
If pathNo <> dr("PathNo") Or equipmentNo <> dr("EquipmentNo") Then
pathNo = dr("PathNo")
equipmentNo = dr("EquipmentNo")
'Count the graphics
diaCount += 1
' Get standard width
upper.Add(dr("Upper"))
lower.Add(dr("Lower"))
End If
' Get the max number of graph points and the number of graphs at that time
If maxPoint < dr("Point") Then
maxPoint = dr("Point")
longestDiaCount = diaCount
End If
Next
Dim x1, x2 As Decimal
Dim y1, y2 As Decimal
' Get the width to draw the reference line
Dim oneHeight As Decimal = Me.recDia.Height / (diaCount + 1)
'Initialize the graph
For i As Integer = 1 To diaCount
x1 = Me.recDia.Left + 1
x2 = Me.recDia.Left + Me.recDia.Width - 1
y1 = Me.recDia.Top + oneHeight * i
' Tolerance range
'※0.01mm/1 Point
Me.gDia.FillRectangle(New SolidBrush(Me.toleranceRecColor) _
, x1 _
, y1 - upper(diaCount - i) * 100 _
, Me.recDia.Width - 1 _
, (upper(diaCount - i) - lower(diaCount - i)) * 100)
' reference line
Me.gDia.DrawLine(New Pen(Me.centerLineColor), x1, y1, x2, y1)
Next
' Determine the drawing magnification of the X-axis so that the max number of points can be displayed
Dim xMag As Decimal = Me.recDia.Width / maxPoint
'Draw a graph
Dim counter As Integer = 0
Dim centerLineY As Decimal
Dim center As Decimal = 0
Dim p As Integer = -1
pathNo = 0 : equipmentNo = 0
For Each dr As DataRow In drs
' Get reference line and reference value
If pathNo <> dr("PathNo") Or equipmentNo <> dr("EquipmentNo") Then
pathNo = dr("PathNo")
equipmentNo = dr("EquipmentNo")
counter += 1
centerLineY = Me.recDia.Top + oneHeight * (diaCount - (counter - 1))
center = dr("Center")
'Draw chart title and reference value
Dim num As New Common.Numeric
Dim numFormat As String = num.GetNumericFormat(1, 2)
Dim s As String = dr("MeasuringTarget").ToString & ControlChars.CrLf
Dim sSize As Size = TextRenderer.MeasureText(Me.gDia, s, Me.Font)
Me.gDia.DrawString(s, Me.Font, Brushes.White, Me.recDia.Left - sSize.Width - 2, centerLineY - sSize.Height / 2)
s = ControlChars.CrLf & Format(center, numFormat)
sSize = TextRenderer.MeasureText(Me.gDia, s, Me.Font)
Me.gDia.DrawString(s, Me.Font, Brushes.White, Me.recDia.Left - sSize.Width - 2, centerLineY - sSize.Height / 2)
x1 = 0 : x2 = 0 : y1 = 0 : y2 = 0 : p = -1
End If
p += 1
'Change the drawing direction and starting point of the graph depending on the number of direction changes
If Me.extRevCnt.Item(pathNo) Mod 2 = 0 Then
x2 = Me.recDia.Left + p * xMag
Else
x2 = Me.recDia.Left + Me.recDia.Width - p * xMag
End If
y2 = centerLineY - (dr("Data") - center) * 100
If p <> 0 Then
'graph drawing
If Me.recDia.Top < y2 And y2 < Me.recDia.Top + Me.recDia.Height Then
' Change the drawing color of the graph for each outer diameter
If counter < Me.diaGraphColor.Count Then
Me.gDia.DrawLine(New Pen(Me.diaGraphColor(counter)), x1, y1, x2, y2)
Else
Me.gDia.DrawLine(New Pen(Me.graphColor), x1, y1, x2, y2)
End If
End If
' out of tolerance
If dr("DataFlag") = Common.Constant.DataFlag.NG Then
Me.gDia.DrawLine(New Pen(Me.ngColor), x1, centerLineY, x2, centerLineY)
End If
'Draw a scale every 10m * However, only when drawing the longest graph
'Drawn for the first graph (normal mandrel diameter)
If counter = 1 Then
If p Mod 100 = 0 Then
Me.gDia.DrawLine(Pens.White, x2, Me.recDia.Top + Me.recDia.Height, x2, Me.recDia.Top + Me.recDia.Height - 3)
Dim s As String = (p \ 10).ToString & "m"
Dim sSize As Size = TextRenderer.MeasureText(Me.gDia, s, Me.Font)
Me.gDia.DrawString(s, Me.Font, Brushes.White, x2 - sSize.Width / 2, Me.recDia.Top + Me.recDia.Height + 2)
End If
End If
Else
' determine the corners of a polygon
Dim points As Point() = {New Point(x2, centerLineY - 10), New Point(x2 - 10, centerLineY - 40), New Point(x2 + 10, centerLineY - 40)}
Me.gDia.FillPolygon(Brushes.Blue, points, System.Drawing.Drawing2D.FillMode.Alternate)
' Display the division number in the circle above
Dim s As String = dr("DivNo").ToString
Dim sSize As Size = TextRenderer.MeasureText(Me.gDia, s, Me.Font)
Me.gDia.DrawString(s, New Font(Me.Font, FontStyle.Regular), Brushes.White, x2 - sSize.Width / 2 + 2, centerLineY - 35)
End If
x1 = x2
y1 = y2
Next
Type.Variable.divideTargetDia = Me.DGVDataDia.SelectedRows.Item(0).Index
Call Me.DrawingGraphDia(Me.DGVDataDia.SelectedRows.Item(0).Index)
Me.PicDiaGraph.Refresh()
End Sub
Here is the code for showing data pointer
Private Sub PicDiaGraph_Paint(ByVal gDia As Graphics)
If IsNothing(tblDataDia) = True Then Exit Sub
If tblDataDia.Rows.Count = 0 Then Exit Sub
If IsNothing(tblEquipmentNoDia) = True Then Exit Sub
If tblEquipmentNoDia.Rows.Count = 0 Then Exit Sub
' Allocate the drawing range according to the number of device numbers
Dim allHeight As Integer = Me.PicDiaGraph.Size.Height
'Drawing range per device number
Dim heightPerEN As Integer = allHeight / (tblEquipmentNoDia.Rows.Count + 1)
' Device number count
Dim count As Integer = 0
' Draw a graph for each device number
For Each rEN As DataRow In tblEquipmentNoDia.Rows
Dim eNo As Integer = rEN("EquipmentNo")
Dim tblSource As DataTable = tblDataDia.Clone
For Each r As DataRow In tblDataDia.Select("EquipmentNo = '" & eNo & "'", "Point ASC")
tblSource.ImportRow(r)
Next
' Acquisition of standard value
Dim tblStandard As New DataTable
If Me.Today = False Then
Dim SQL As String = ""
SQL &= "SELECT Standard.Center "
SQL &= "FROM Standard "
SQL &= "WHERE Standard.EquipmentNo = " & eNo & " And Standard.MfgID = '" & barcodeNo.Trim & "' "
SQL &= "GROUP BY Standard.Center;"
daDia = New OleDb.OleDbDataAdapter(SQL, cnMdbDia)
daDia.Fill(tblStandard)
Else
'
End If
Dim center As Single = Format(tblStandard.Rows(0)("center"), "0.00")
' Drawing start position (height)
Dim shift As Integer = heightPerEN * count
'get width of data
Dim margin As Integer = 0
_xMaxDia = tblSource.Select("Point = MAX(Point)")(0)("Point")
_xMinDia = tblSource.Select("Point = MIN(Point)")(0)("Point")
Dim yMax As Single = tblSource.Select("Data = MAX(Data)")(0)("Data")
Dim yMin As Single = tblSource.Select("Data = MIN(Data)")(0)("Data")
'Width on X-axis data
Dim xRange As Integer = _xMaxDia - _xMinDia
'Width on Y-axis data
Dim yRange As Single = yMax - yMin
'Get size of control
Dim height As Integer = heightPerEN - (margin * 2)
Dim width As Integer = Me.PicDiaGraph.Size.Width - 21
' Nominal length per unit
_xUnitDia = width / xRange
Dim yUnit As Single = 200
'graph drawing
For i As Integer = 0 To tblSource.Rows.Count - 2
Dim x1 As Decimal = Me.recDia.Left + 1
' starting point data
Dim row1 As DataRow = tblSource.Rows(i)
Dim point1 As Integer = row1("Point")
Dim data1 As Single = row1("Data")
' end point data
Dim row2 As DataRow = tblSource.Rows(i + 1)
Dim point2 As Integer = row2("Point")
Dim data2 As Single = row2("Data")
If point2 < point1 Then MessageBox.Show("X")
Me.gDia.DrawLine(Pens.White, _
CInt((point1 - _xMinDia) * _xUnitDia), _
height - (data1 - center) * yUnit + margin + shift, _
CInt(point2 - _xMinDia) * _xUnitDia, _
height - (data2 - center) * yUnit + margin + shift)
Next
count += 1
Next
End Sub
The problem might appear in this code

VBA- Printing in For loop

I'm trying to find and remove outliers from many columns of data, but it doesn't clear the cells that contain the outliers when I run the code. I tried just printing "colLength" within the first For loop, and that did nothing either. Advice on where I went wrong or how I might be able to fix it?
Sub Outliers()
Dim calc As Worksheet
Set calc = ThisWorkbook.Sheets("Sheet2")
Dim num As Double
Dim x As Integer
Dim y As Integer
Dim colLength As Integer
'Variables for upper fence, lower fence, first quartile, third quartile, and interquartile range
Dim upper As Double
Dim lower As Double
Dim q1 As Double
Dim q3 As Double
Dim interquartRange As Double
For y = 1 To y = 49
'Find last row of the column
colLength = calc.Cells(Rows.count, y).End(xlUp).Row
'Calculate first and third quartiles
q1 = Application.WorksheetFunction.Quartile(Range(Cells(2, y), Cells(colLength, y)), 1)
q3 = Application.WorksheetFunction.Quartile(Range(Cells(2, y), Cells(colLength, y)), 3)
interquartRange = q3 - q1
'Calculate upper and lower fences
upper = q3 + (1.5 * interquartRange)
lower = q1 - (1.5 * interquartRange)
For x = 2 To x = colLength
num = calc.Cells(x, y)
'Remove outliers
If num > upper Or num < lower Then
Range(calc.Cells(x, y)).ClearContents
End If
Next x
Next y
End Sub
For y = 1 To y = 49 should be For y = 1 To 49. Similarly For x = 2 To x = colLength should be For x = 2 To colLength
Try this in a new module and you will see and understand the difference ;)
Dim Y As Long
Sub SampleA()
For Y = 1 To Y = 49
Debug.Print Y
Next Y
End Sub
Sub SampleB()
For Y = 1 To 49
Debug.Print Y
Next Y
End Sub

VBA - Modular exponentiation

I've been trying to do Modular exponentiation in VBA for use in MS excel, but there seems to be a logical error which crashes Excel everytime i try to use the formula.
Function expmod(ax As Integer, bx As Integer, cx As Integer)
' Declare a, b, and c
Dim a As Integer
Dim b As Integer
Dim c As Integer
' Declare new values
Dim a1 As Integer
Dim p As Integer
' Set variables
a = ax
b = bx
c = cx
a1 = a Mod c
p = 1
' Loop to use Modular exponentiation
While b > 0
a = ax
If (b Mod 2 <> 0) Then
p = p * a1
b = b / 2
End If
a1 = (a1 * a1) Mod c
Wend
expmod = a1
End Function
I used the pseudocode which was provided here.
Here is an implementation I wrote a while back. Using Long rather than Integer enables it to handle higher exponents:
Function mod_exp(alpha As Long, exponent As Long, modulus As Long) As Long
Dim y As Long, z As Long, n As Long
y = 1
z = alpha Mod modulus
n = exponent
'Main Loop:
Do While n > 0
If n Mod 2 = 1 Then y = (y * z) Mod modulus
n = Int(n / 2)
If n > 0 Then z = (z * z) Mod modulus
Loop
mod_exp = y
End Function

Finding minimum point of a function

If I have a convex curve, and want to find the minimum point (x,y) using a for or while loop. I am thinking of something like
dim y as double
dim LastY as double = 0
for i = 0 to a large number
y=computefunction(i)
if lasty > y then exit for
next
how can I that minimum point? (x is always > 0 and integer)
Very Close
you just need to
dim y as double
dim smallestY as double = computefunction(0)
for i = 0 to aLargeNumber as integer
y=computefunction(i)
if smallestY > y then smallestY=y
next
'now that the loop has finished, smallestY should contain the lowest value of Y
If this code takes a long time to run, you could quite easily turn it into a multi-threaded loop using parallel.For - for example
dim y as Double
dim smallestY as double = computefunction(0)
Parallel.For(0, aLargeNumber, Sub(i As Integer)
y=computefunction(i)
if smallestY > y then smallestY=y
End Sub)
This would automatically create separate threads for each iteration of the loop.
For a sample function:
y = 0.01 * (x - 50) ^ 2 - 5
or properly written like this:
A minimum is mathematically obvious at x = 50 and y = -5, you can verify with google:
Below VB.NET console application, converted from python, finds a minimum at x=50.0000703584199, y=-4.9999999999505, which is correct for the specified tolerance of 0.0001:
Module Module1
Sub Main()
Dim result As Double = GoldenSectionSearch(AddressOf ComputeFunction, 0, 100)
Dim resultString As String = "x=" & result.ToString + ", y=" & ComputeFunction(result).ToString
Console.WriteLine(resultString) 'prints x=50.0000703584199, y=-4.9999999999505
End Sub
Function GoldenSectionSearch(f As Func(Of Double, Double), xStart As Double, xEnd As Double, Optional tol As Double = 0.0001) As Double
Dim gr As Double = (Math.Sqrt(5) - 1) / 2
Dim c As Double = xEnd - gr * (xEnd - xStart)
Dim d As Double = xStart + gr * (xEnd - xStart)
While Math.Abs(c - d) > tol
Dim fc As Double = f(c)
Dim fd As Double = f(d)
If fc < fd Then
xEnd = d
d = c
c = xEnd - gr * (xEnd - xStart)
Else
xStart = c
c = d
d = xStart + gr * (xEnd - xStart)
End If
End While
Return (xEnd + xStart) / 2
End Function
Function ComputeFunction(x As Double)
Return 0.01 * (x - 50) ^ 2 - 5
End Function
End Module
Side note: your initial attempt to find minimum is assuming a function is discrete, which is very unlikely in real life. What you would get with a simple for loop is a very rough estimate, and a long time to find it, as linear search is least efficient among other methods.

How to generate Fibonacci series?

I am a beginner for programming and dealing with concept of visual basic 2010 to generate the following Fibonacci series output that will get the next number by adding two consecutive numbers
I have tried that by creating variables like bellow
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As Integer = 0
Dim b As Integer = 1
Dim fib As Integer = 0
Do
fib = a + b
a = b
b = fib
Label1.Text = Label1.Text + fib.ToString & ControlChars.NewLine
Loop While fib < 55
End Sub
End Class
This should work
Dim a As Integer = 0
Dim b As Integer = 1
Dim fib As Integer
Do
Label1.Text += a.ToString & ControlChars.NewLine
fib = a + b
a = b
b = fib
Loop While a <= 55
Private Sub Command1_Click()
Dim x, g, n, i, sum As Integer
n = Val(Text1.Text)
x = 0
y = 1
Print x
Print y
For i = 3 To n
sum = x + y
Print sum
x = y
y = sum
y = sum
Next i
End Sub
Here the solution:
Dim num1 As Integer = 1
Dim num2 As Integer = 1
Dim aux As Integer
Console.Write(num1)
Console.Write(", ")
Console.Write(num2)
Console.Write(", ")
While num1 < 100
aux = num1 + num2
Console.Write(aux)
Console.Write(", ")
num1 = num2
num2 = aux
End While
This print Fibonacci series till number 100
I hope this help you!