logic is correct but output is not - vb.net

It is a function that converts decimal into binary. It is not converting values to binary correctly. This gives 10101 for 19 instead of 10011. How can it be corrected?
Function Binary(n As Integer)
If n = 0 Or n = 1 Then
Console.Write(n)
Else
Binary(n / 2)
Console.Write(n Mod 2)
End If
End Function
Sub Main()
Dim n As Integer
Console.Write("Enter Number: ")
n = Console.ReadLine()
Console.Write(Binary(n))
Console.ReadKey()
End Sub

This is something that might drive you crazy because of how small it is, but the problem is with which division operator you use.
Doing it with Binary(n / 2) treats the integer as a double and passes 9.5 to Binary, while Binary(n \ 2) is the designated integer division operator. You can read more about Arithmetic Operators on Microsoft's website.
Here's what I ran:
Module Module1
Function Binary(n As Integer)
If n = 0 Or n = 1 Then
Console.Write(n)
Else
Binary(n \ 2)
Console.Write(n Mod 2)
End If
End Function
Sub Main()
Dim n As Integer
Console.Write("Enter Number: ")
n = Console.ReadLine()
Console.Write(Binary(n))
Console.ReadKey()
End Sub
End Module
Output for 19: 10011

Related

How can I solve my "sub main was not found" problem?

Module PrimePairs
Public Function IsPrime(n As Long) As Boolean
Console.WriteLine("Please enter the value: ")
n = Console.ReadLine()
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
Public Function PrimePairs(ByVal n As Long, ByVal n2 As Long) As Integer
Dim count As Integer = 0
Console.ReadLine()
If n Mod 2 = 0 Then
For i = 1 To (n / 2) + 1
n2 = n - i
If IsPrime(i) And IsPrime(n2) = True Then
count += 1
End If
Next
Else
n2 = n - 2
If IsPrime(n2) = True Then
count = +1
End If
End If
Console.WriteLine("The result is:", count)
Return n
End Function
End Module
I want my code to calculate how many prime number twins can write the input I gave.
The problem is that your project actually does not contain a Sub Main(), as the error states.
You defined two functions in the Module Program, but console applications need a predefined entry point, which usually is the Main method.
The compiler is telling you that your project is not valid because it didn't find any entry point.
Just add a Sub Main() to get your project working, then call your functions from that method.
Example:
Option Strict On
Module Program
Sub Main(args As String())
Console.WriteLine("Please enter the value: ")
Dim input As String = Console.ReadLine()
Dim number As Long
If Long.TryParse(input, number) Then // More about this function in the answer below
Dim prime As Boolean = IsPrime(number)
If prime Then
Console.WriteLine(number & " is prime.")
Else
Console.WriteLine(number & " is not prime.")
End If
End If
Console.ReadLine()
End Sub
Function IsPrime(n As Long) As Boolean
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long = 2
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
End Module
Also, I suggest you to enable Option Strict On as I added at the beginning of file. This prevents the compiler from doing implicit casts and forces you to explicitly declare your variables.
E.g., your line of code
n = Console.ReadLine()
is not valid with Option Strict On, because n is supposed to be a long, but Console.ReadLine() returns a string.
If you are a beginner, this will allow you to better understand how programming works and will help you to avoid errors - take good habits from the beginning, you can thank me later ;)
That's why I changed your code withLong.TryParse(input, number): this function returns true if provided input can be cast (=converted) to a long, and assigns the casted value to number variable.
There's a lot more I'd like to suggest you, but I would go off-topic.

How to stop any decimals rounding up in visual basics 2017?

So I'm doing this thing from the visual basics 2017 book where a table can hold 8 guests max and everything works fine except for when I have guest numbers that go up by factors of 4 (except factors of 8). 1 guest gives me 1 table but when I put 4 guest it gives me 2 and stays that way until I put 8 guests.
If dblGuest Mod dblTable = 0 Then
dblTotal = dblGuest / dblTable
ElseIf dblGuest Mod dbltable <> 0 Then
dblTotal = dblGuest / 8 + 1
End If
Given that you're using Mod, I would assume that you want integer division, rather than floating-point division. In that case, use \, which is the integer division operator, rather than /.
Personally, I'd be doing it something like this:
Module Module1
Sub Main()
Const guestCountPerTable As Integer = 8
For guestCount = 0 To 40
Console.WriteLine($"{guestCount} guest(s) requires {GetTableCount(guestCount, guestCountPerTable)} table(s)")
Next
End Sub
Private Function GetTableCount(guestCount As Integer, guestCountPerTable As Integer) As Integer
Dim tableCount = guestCount \ guestCountPerTable
If guestCount Mod guestCountPerTable <> 0 Then
tableCount += 1
End If
Return tableCount
End Function
End Module
You could also use the Math.DivRem method:
Module Module1
Sub Main()
Const guestCountPerTable As Integer = 8
For guestCount = 0 To 40
Console.WriteLine($"{guestCount} guest(s) requires {GetTableCount(guestCount, guestCountPerTable)} table(s)")
Next
End Sub
Private Function GetTableCount(guestCount As Integer, guestCountPerTable As Integer) As Integer
Dim remainder As Integer
Dim tableCount = Math.DivRem(guestCount, guestCountPerTable, remainder)
If remainder <> 0 Then
tableCount += 1
End If
Return tableCount
End Function
End Module

Reverse a string of numbers using a while loop (VB)

I am fairly new to coding in VB and I am trying to reverse the string of numbers in the variable 'binary' by using a while loop (at the bottom of the code) but when the program runs I get a System.IndexOutOfRangeException error. What changes do I need to make to fix this?
Thanks
Module Module1
Sub Main()
Dim denary As Integer
Dim binary As String = " "
Dim x As Integer
Dim y As Integer = 0
Console.WriteLine("What is the denary number?") 'Asks the user what number denary number they want converted
denary = Console.Read()
While denary > 0 'Calculates the binary number, but reversed
If denary Mod 2 = 0 Then
binary = binary + "0"
denary = denary / 2
Else
binary = binary + "1"
denary = denary / 2
End If
End While
Console.WriteLine("The binary equivalent is:" & binary) 'Prints the binary number in reverse
Console.ReadLine()
x = Len(binary)
While x > 0
Console.WriteLine(binary(x)) 'Print the correct binary equivalent (Not working)
Console.ReadLine()
x = x - 1
End While
End Sub
End Module
Array indexes start at 0, so the last one is always 1 less than the length of the array:
x = Len(binary) - 1
While x >= 0
'...

Recursive factorial output

I'm trying to write a recursive function through a vb console application that will output the factorial or a number between 1 and 10. I get a System.StackOverflowException when I run it. Can anyone help explain what I've done wrong?
Module Module1
Dim Number As Byte
Sub Main()
Console.WriteLine("Write a number from 1-10")
Number = Console.ReadLine()
FactorialCalc()
End Sub
Function FactorialCalc()
Dim Counter As Byte
Dim A As Byte
' Dim Factorial As Integer
Do
If Number < 1 Or Number > 10 Then
Console.WriteLine("Please select a number from 1-10")
End If
Loop Until Number >= 1 And Number <= 10
A = Number
Do
FactorialCalc = Number * FactorialCalc(Number - 1)
Counter = Counter + 1
Loop Until Counter = A + 1
Console.WriteLine(FactorialCalc.value)
Console.ReadLine()
End Function
End Module
A factorial program shouldn't be all this long. All you need is:
Module Module1
Dim Number As Integer
Sub Main()
Do
Console.WriteLine("Write a number from 1-10")
Number = Console.ReadLine()
Loop Until Number >= 1 And Number <= 10
Dim Result = FactorialCalc()
Console.WriteLine(Result)
Console.ReadLine()
End Sub
Function FactorialCalc(num as Integer) As Integer
Return num * If(num > 2, FactorialCalc(num - 1), 2)
End Function
End Module
your recursive call to FactorialCalc(Number - 1) is going to keep getting called endlessly, there by exhausting your stack space. The condition to break out of the recursion is after your recursive call and so control never reaches the point beyond the call to the recursive function and keeps calling it over and over again.

How to represent a number in the form of A*10-^n?

I recently wrote this program in Visul Basic 13.
it searchs for the nth catalan number but after 48 even Decimal type is too short.
Is there any other way to represent them? like in the form of A*10^n?
Public Class Try_Catalan_Number
'Catalan numbers form a sequence of natural numbers that occur in various counting problems,
'often involving recursively defined objects.
Inherits Base_Number
Public Overrides Sub Test()
Dim Return_Catalan_Value As Decimal
If Function_Catalan(Return_Catalan_Value) = False Then
Return_To_Form_Boolean = False
Else
Return_To_Form_Boolean = True
End If
Return_To_Form_Value = Function_Catalan(Return_Catalan_Value)
End Sub
Private Function Function_Catalan(Return_Catalan_Value As Decimal) As Decimal
'We return a Decimal function because catalan numbers can be very big and decimal is the biggest type.
Dim Binomial_Cofficients As Decimal
Dim Result As Decimal
Dim Number_Of_Loops As Integer
Dim tmpNumber As Object
Dim K As Decimal
Dim N As Decimal
If (Number > 48) Then
Return False
Exit Function
End If
'48 is the largest catalan number position which can be displayed...any position above 48 is too big.
tmpNumber = Number - 1
N = 2 * tmpNumber
K = tmpNumber
Result = 1
For Number_Of_Loops = 1 To K
Result = Result * (N - (K - Number_Of_Loops))
Result = Result / Number_Of_Loops
Next Number_Of_Loops
Binomial_Cofficients = Result
tmpNumber = Number - 1
tmpNumber = ((1 / (1 + tmpNumber)) * Binomial_Cofficients)
Return_Catalan_Value = tmpNumber
Return Return_Catalan_Value
End Function
End Class
[I assume by "Visul Basic 13" you mean the VB which is associated with Visual Studio 2013, i.e. VB version 12.0.]
You can use System.Numerics.BigInteger (you'll have to add a reference to System.Numerics):
Imports System.Numerics
Module Module1
Friend Function Factorial(n As Integer) As BigInteger
If n < 2 Then Return 1
If n = 2 Then Return 2
Dim f As BigInteger = BigInteger.Parse("2")
For i = 3 To n
f *= i
Next
Return f
End Function
Friend Function CatalanNumber(n As Integer) As BigInteger
Return Factorial(2 * n) / (Factorial(n + 1) * Factorial(n))
End Function
Sub Main()
For i = 0 To 550
Console.WriteLine(CatalanNumber(i).ToString())
Next
Console.ReadLine()
End Sub
End Module
I did not test to see the maximum Catalan number it can calculate, and I have no inclination to verify the results beyond those shown on the Wikipedia page.
Optimisations are left as an exercise for the reader ;)
Edit: FWIW, I can get it to run a bit faster by using
Function CatalanNumber(n As Integer) As BigInteger
Dim nFactorial = Factorial(n)
Dim twonFactorial = nFactorial
For i = (n + 1) To 2 * n
twonFactorial = BigInteger.Multiply(twonFactorial, i)
Next
Return twonFactorial / (BigInteger.Pow(nFactorial, 2) * (n + 1))
End Function
The speed increase varies from roughly 50% (n=50) to 20% (n=5000). If you're only using the function a few times for fairly small n, there may be little point worrying about it.
Edit2 Re-writing your function a bit to make it easier to read and removing the off-by-one error, we get:
Private Function Function_Catalan(a As Integer) As BigInteger
If a = 0 Then Return 1
Dim binomialCofficient As BigInteger = BigInteger.One
Dim n As Integer = 2 * a
Dim k As Integer = a - 1
For i As Integer = 1 To k
binomialCofficient = binomialCofficient * (n - (k - i)) / i
Next i
Return binomialCofficient / a
End Function
to get this format you could use:
String.Format("{0:E4}", InputNumber)