How to find a position in a integer - vb.net

If I had a integer that was, for example 11110011. How would I find out what number was in each position so I could use them calculate something. Thanks

cast it to String and then use method of string to find the int at a particular position.

Feel free to read a bit about operators if you wish.
Anyhow i'd use a loop of Mod 10 and divide by 10 each iteration.
Pseudo code:
Given number
While number is not zero
Get the mod 10 of the number
... Do what you need to do with it - that's the digit
Divide by 10.
Repeat.
Done.
for example:
Dim yourNumber As Integer = 12930 // for example.
While index >0
Dim digit As Integer = yourNumber Mod 10
Debug.Write(digit.ToString & " ")
index /= 1
End While
Will write all the digits, seperated by a space:
output: 1 2 3 9 0

Related

Why does the "Double" data type mess up my Fibonacci sequence?

I am trying to write a program which gives me the index of the first 1000-digit number in the Fibonacci sequence. I have set the data type as "Double" because I need to store the long numbers, however the output I get isn't right?
I have tried setting the "num" data type as "integer", "long" and even "int64", but all these just give me an overflow error after about 2 seconds.
Dim num, prev, temp, index As Double
Sub Main()
num = 1
prev = 1
temp = 1
index = 1
While Len(num) < 1000
Console.WriteLine(num)
temp = num
num += prev
prev = temp
index += 1
End While
Console.WriteLine(index)
Console.ReadLine()
End Sub
I would expect the program to output the Fibonacci sequence until it finds the first 1000-digit number, and then it will output the index of it. However, I just get an output of loads of decimal numbers (to about 20 decimal points) and then it outputs 8. Forever.
I am truly stumped. Any ideas?
The precision of a double data type does not allow you to store so many digits.
If you use BigInteger you can store as many digits as you can, as the data type grows its storage according to your needs.
Additionally, as suggested by the comments, a quick and dirty way to stop after 1000 digits is to have the number converted to string and check its length. This way you are not using mathematical operations which would result in an overflow.
Your code should look like the following:
Dim num, prev, temp, index As BigInteger
Sub Main()
num = 1
prev = 1
temp = 1
index = 1
While BigInteger.Log10(num) <= 999
Console.WriteLine(num)
temp = num
num += prev
prev = temp
index += 1
End While
Console.WriteLine(index)
Console.ReadLine()
End Sub
It all comes down to no data types in vb being able to hold a 1000 digit number. If I were you I would have an array with 1000 items and have each item be a digit.

How do you get the number that is in the center of numbers entered in a textbox vb.net

For example I entered the numbers "31572" in a textbox then it will get the number "5". Also if I enter numbers with the length of even numbers like "123752" then it will get the "37" which is in the center of the entered numbers. I have no idea what to with this, so I'm hoping someone gives me an idea. Thank you :)
Since you want to take from the string 2 chars when the string length is even and 1 char when it's odd, you just need to care about the remainder of the division by 2.
Using Integer division (3 \ 2 = 1):
If String.Length Mod 2 = 0, take 2 chars, starting from String.Length \ 2 - 1
If String.Length Mod 2 = 1, take 1 chars, starting from String.Length \ 2
You may want to add a null check and just return the original string if the string length is less than 3 (when the string is "1" or "12", return the string as it is).
Your code could be:
Dim result as string = GetCenterValue(TextBox1.Text)
Public Function GetCenterValue(content As String) As String
If String.IsNullOrEmpty(content) Then Return String.Empty
Dim sLength As Integer = content.Length
If sLength < 3 Then Return content
Return content.Substring(sLength \ 2 - (1 - sLength Mod 2), 2 - sLength Mod 2)
End Function
As the content of the TextBox object is a text, simply take the text, check its length: if it's an even number halves that number and take that character and the following, if not, halves that number, round it up and take that character only. To check if a number is even use Mod operator (n Mod 2), if the result is 0 the number is even. Remember that Substring uses 0-based index.

Rounding a variable to an integer

I have a calculation like this: 3 * 12300 / 160. The result is: 230.625. But I just want the integer part, 230.
In C, this can be done using something like this: int MyVar = (int)3*12300/160;
Is there a way in VBA (With MS-Access) for force the result to be an integer?
You can round down using the Int or Fix functions.
Since you know the result you want is a whole number, you should store the result in a variable of type Long (or Integer if you're absolutely certain it will always be smaller than 32768).
Dim l As Long
l = Int(3 / 160 * 12300) ' <~~~~ Yes, I switched the numbers around on purpose!*
MsgBox "l = " & l
* Why did I switch the numbers around? Because the expression 3 * 12300 / 160 will throw an error in VBA. Read here why: Overflow when multiplying Integers and assigning to Long

.NET - How to generate random numbers in a range with a certain step size?

I'd like to generate random numbers in a range (say between 0 and 1) - but with a certain step size (say 0.05).
There's a python function that does exactly that:
random.randrange ( [start,] stop [,step] )
So my problem is not how to generate random numbers in a range - instead I need a way to do this with a certain step size.
How can this be done in .NET?
You could generate a random integer between 0 and 20 and divide the result by 20
Dim rnd = New Random()
Dim nextValue = rnd.Next(21) / 20
This will give you a random number between 0 and 1 (inclusive) in 0.05 increments
You can try something like that:
Dim objRandom As New System.Random
Label1.Text = Math.Round(objRandom.NextDouble() * 2, 1) / 2
So you create a random double and you round it to one digit (example: 0.8).
Then you divided it with 2 and you get what you want

Recognizing when to use the modulus operator

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?
I know I can use the modulus operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the modulus operator is useful, and I would like to learn to take advantage of it.
I just have problems identifying where the modulus operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "Hey! The remainder of division would work here!".
Imagine that you have an elapsed time in seconds and you want to convert this to hours, minutes, and seconds:
h = s / 3600;
m = (s / 60) % 60;
s = s % 60;
0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;
Did you see what it did? At the last step it went back to zero. This could be used in situations like:
To check if N is divisible by M (for example, odd or even)
or
N is a multiple of M.
To put a cap of a particular value. In this case 3.
To get the last M digits of a number -> N % (10^M).
I use it for progress bars and the like that mark progress through a big loop. The progress is only reported every nth time through the loop, or when count%n == 0.
I've used it when restricting a number to a certain multiple:
temp = x - (x % 10); //Restrict x to being a multiple of 10
Wrapping values (like a clock).
Provide finite fields to symmetric key algorithms.
Bitwise operations.
And so on.
One use case I saw recently was when you need to reverse a number. So that 123456 becomes 654321 for example.
int number = 123456;
int reversed = 0;
while ( number > 0 ) {
# The modulus here retrieves the last digit in the specified number
# In the first iteration of this loop it's going to be 6, then 5, ...
# We are multiplying reversed by 10 first, to move the number one decimal place to the left.
# For example, if we are at the second iteration of this loop,
# reversed gonna be 6, so 6 * 10 + 12345 % 10 => 60 + 5
reversed = reversed * 10 + number % 10;
number = number / 10;
}
Example. You have message of X bytes, but in your protocol maximum size is Y and Y < X. Try to write small app that splits message into packets and you will run into mod :)
There are many instances where it is useful.
If you need to restrict a number to be within a certain range you can use mod. For example, to generate a random number between 0 and 99 you might say:
num = MyRandFunction() % 100;
Any time you have division and want to express the remainder other than in decimal, the mod operator is appropriate. Things that come to mind are generally when you want to do something human-readable with the remainder. Listing how many items you could put into buckets and saying "5 left over" is good.
Also, if you're ever in a situation where you may be accruing rounding errors, modulo division is good. If you're dividing by 3 quite often, for example, you don't want to be passing .33333 around as the remainder. Passing the remainder and divisor (i.e. the fraction) is appropriate.
As #jweyrich says, wrapping values. I've found mod very handy when I have a finite list and I want to iterate over it in a loop - like a fixed list of colors for some UI elements, like chart series, where I want all the series to be different, to the extent possible, but when I've run out of colors, just to start over at the beginning. This can also be used with, say, patterns, so that the second time red comes around, it's dashed; the third time, dotted, etc. - but mod is just used to get red, green, blue, red, green, blue, forever.
Calculation of prime numbers
The modulo can be useful to convert and split total minutes to "hours and minutes":
hours = minutes / 60
minutes_left = minutes % 60
In the hours bit we need to strip the decimal portion and that will depend on the language you are using.
We can then rearrange the output accordingly.
Converting linear data structure to matrix structure:
where a is index of linear data, and b is number of items per row:
row = a/b
column = a mod b
Note above is simplified logic: a must be offset -1 before dividing & the result must be normalized +1.
Example: (3 rows of 4)
1 2 3 4
5 6 7 8
9 10 11 12
(7 - 1)/4 + 1 = 2
7 is in row 2
(7 - 1) mod 4 + 1 = 3
7 is in column 3
Another common use of modulus: hashing a number by place. Suppose you wanted to store year & month in a six digit number 195810. month = 195810 mod 100 all digits 3rd from right are divisible by 100 so the remainder is the 2 rightmost digits in this case the month is 10. To extract the year 195810 / 100 yields 1958.
Modulus is also very useful if for some crazy reason you need to do integer division and get a decimal out, and you can't convert the integer into a number that supports decimal division, or if you need to return a fraction instead of a decimal.
I'll be using % as the modulus operator
For example
2/4 = 0
where doing this
2/4 = 0 and 2 % 4 = 2
So you can be really crazy and let's say that you want to allow the user to input a numerator and a divisor, and then show them the result as a whole number, and then a fractional number.
whole Number = numerator/divisor
fractionNumerator = numerator % divisor
fractionDenominator = divisor
Another case where modulus division is useful is if you are increasing or decreasing a number and you want to contain the number to a certain range of number, but when you get to the top or bottom you don't want to just stop. You want to loop up to the bottom or top of the list respectively.
Imagine a function where you are looping through an array.
Function increase Or Decrease(variable As Integer) As Void
n = (n + variable) % (listString.maxIndex + 1)
Print listString[n]
End Function
The reason that it is n = (n + variable) % (listString.maxIndex + 1) is to allow for the max index to be accounted.
Those are just a few of the things that I have had to use modulus for in my programming of not just desktop applications, but in robotics and simulation environments.
Computing the greatest common divisor
Determining if a number is a palindrome
Determining if a number consists of only ...
Determining how many ... a number consists of...
My favorite use is for iteration.
Say you have a counter you are incrementing and want to then grab from a known list a corresponding items, but you only have n items to choose from and you want to repeat a cycle.
var indexFromB = (counter-1)%n+1;
Results (counter=indexFromB) given n=3:
`1=1`
`2=2`
`3=3`
`4=1`
`5=2`
`6=3`
...
Best use of modulus operator I have seen so for is to check if the Array we have is a rotated version of original array.
A = [1,2,3,4,5,6]
B = [5,6,1,2,3,4]
Now how to check if B is rotated version of A ?
Step 1: If A's length is not same as B's length then for sure its not a rotated version.
Step 2: Check the index of first element of A in B. Here first element of A is 1. And its index in B is 2(assuming your programming language has zero based index).
lets store that index in variable "Key"
Step 3: Now how to check that if B is rotated version of A how ??
This is where modulus function rocks :
for (int i = 0; i< A.length; i++)
{
// here modulus function would check the proper order. Key here is 2 which we recieved from Step 2
int j = [Key+i]%A.length;
if (A[i] != B[j])
{
return false;
}
}
return true;
It's an easy way to tell if a number is even or odd. Just do # mod 2, if it is 0 it is even, 1 it is odd.
Often, in a loop, you want to do something every k'th iteration, where k is 0 < k < n, assuming 0 is the start index and n is the length of the loop.
So, you'd do something like:
int k = 5;
int n = 50;
for(int i = 0;i < n;++i)
{
if(i % k == 0) // true at 0, 5, 10, 15..
{
// do something
}
}
Or, you want to keep something whitin a certain bound. Remember, when you take an arbitrary number mod something, it must produce a value between 0 and that number - 1.