The sum of the first natural 100 numbers - vb.net

new to coding,
Quick Homework problem Im having trouble on.
I must find the sum of the first 100 natural numbers. 1+2+3+4, and so on. While using "while loops".
This is what I have so far.
Dim sum, count As Integer
Const num As Integer = 1
Console.WriteLine("The Sum of the first 100 natural numbers is:")
count = num + 1
While count <= 100
Count = num + count
End While
Sum = count
Console.WriteLine("{0}", sum)
Console.ReadLine()
I know for a fact the math and while loop is incorrect, but Im not sure how to fix it. I keep getting 101 as my answer.

You do not need the num constant and the line: count = num + 1
While count <= 100
sum += count
count += 1
End While

I know you are learning and the solution must use a While loop but for fun see what you can do in 2 lines of code.
Dim arrNumbers = Enumerable.Range(1, 100).ToArray
Console.WriteLine(arrNumbers.Sum)

Since your question title asked for sums of all [1 - 100] as well as the evens and odds, here is some LINQ for each one
Dim sum = Enumerable.Range(1, 100).Sum()
Dim sumEvens = Enumerable.Range(1, 100).Sum(Function(i) If(i Mod 2 = 0, i, 0))
Dim sumOdds = Enumerable.Range(1, 100).Sum(Function(i) If(i Mod 2 = 0, 0, i))
Console.WriteLine($"Sum: {sum}, Sum evens: {sumEvens}, Sum odds: {sumOdds}")
Sum: 5050, Sum evens: 2550, Sum odds: 2500
Enumerable.Range(1, 100) creates your sequence of all [1 - 100]. Call the LINQ function Sum to simply get the sum, or you can pass a lambda function to Sum to transform the numbers. Use Mod to select evens or odds. The method above sets odds to 0 for the evens, and vice-versa for the odds.
An alternative to this method of transforming the sequence is to use Where to select only even numbers then Sum, which may be more readable.
Dim sumEvens = Enumerable.Range(1, 100).Where(Function(i) i Mod 2 = 0).Sum()

With your code you've done a few things in a weird way.
Let's simplify the code and see what's going wrong.
To start with you are setting num as a constant to the value of 1. Since it's not changing, we'll put the value in directly.
You'd then have this:
count = 1 + 1
While count <= 100
count = 1 + count
End While
sum = count
So that means count will start at 2 and goes up by one until the value of count is greater than 100 - and that's when it is 101.
Then you set sum to count and you get 101.
What you needed to do was start count as 1 and sum up the values inside the loop.
count = 1
While count <= 100
sum = sum + count
count = count + 1
End While
And that gives the correct result of 5050.

While count <= 100
num += count
count += 1
End While
Sum = num

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 to find the largest number among 5 in visual basic?

I want to find it using the IF statements and NESTED IF statements. I know how to find the largest among 3 numbers, but can't do the 5. I want to follow the same concept as the code below:
Dim number1, number2, number3, largest as integer
number1= 2
number 2= 7
number3= 14
If number1>number2 then
if number1>number 3 then
largest= number1
else
largest= number3
End If
Else If number2> number3 then
largest= number2
else
largest number3
End If
label1.text= largest
By comparing each number to largest and only assigning it if it's larger you will end up with the largest number assigned to largest.
Dim number1, number2, number3, largest As Integer
number1 = 2
number2 = 7
number3 = 14
' if 2 > 0 then largest = 2
If number1 > largest Then largest = number1
' if 7 > 2 then largest = 7
If number2 > largest Then largest = number2
' if 14 > 7 then largest = 14
If number3 > largest Then largest = number3
label1.text = largest
The logic requires some re-thinking. At the moment you are using a brute force approach which, as you have already discovered, becomes more complicated the larger the original set. And your solution is not really maintainable - what if you wanted 4 numbers, 10 numbers etc, you would have to rewrite code all the time.
Modern coding languages include loops and collections to make our lives easier.
Function MyMax(Numbers() As Long) As String
Dim largest As Long = Long.MinValue
If Numbers.Count > 0 Then ' it is ok to find the maximum from a single number!
For iterator = 0 To Numbers.Count - 1
If Numbers(iterator) > largest Then largest = Numbers(iterator)
'largest = If(Numbers(iterator) > largest, Numbers(iterator), largest) ' another way of achieving the line above
Next
Return largest.ToString
Else
Return "Error - no numbers to check!"
End If
End Function
Sub testMyMax()
Debug.Print(MyMax({2, 7, 14}))
End Sub

How can i choose random number smaller than "1000" or "n" in vb?

How can i choose random number smaller than "1000" or "n"?
Do While ddd <> 1
Static staticRandomGenerator As New System.Random
max += 1
dd = staticRandomGenerator.Next(If(min > max, max, min), If(n > max, min, max))
ddd = ee * dd Mod z
Loop
How can i add this condition to this code? Any idea?
There are two ways to generate a random number in VB.NET (that I am familiar with).
Technique 1:
randomNumber = CInt(Math.Floor((n - 0 + 1) * Rnd())) + 0
n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.
0 = Lowerbound value, otherwise known as the lowest value the randomNumber can be.
You can find more info about this technique here.
Technique 2:
Dim rn As New Random
randomNumber = rn.Next(0, n)
Again, n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.
And again, 0 = Lowerbound value, otherwise known as the lowest value randomNumber can be.
I cannot find a link to an official post about this on the Microsoft MSDN site, but if anyone can find a good post about this technique, please comment, or message me.
I hope this helps!

Linq statement vs For loop in VB.NET for Project Euler P1: why the result is different?

I am just trying to experience myself the use of For Loop vs. Linq statement in VB.NET. However, I've found a difference in a result of which I found interesting, but had no clue why it 's happening. (I am trying to find the sum of all the multiples of 3 or 5 below 1000.) Below are my two ways of doing that:
method 1: For loop
Dim sum1 As Integer = 0
For i As Integer = 0 To 999
If i Mod 3 = 0 Or i Mod 5 = 0 Then
sum1 += i
End If
Next
Method 2: Linq statement
Dim sum2 As Integer = Enumerable.Range(0, 999).Where(Function(x As Integer) x Mod 3 = 0 Or x Mod 5 = 0).Sum
Obviously method 2 is shorter and of more functional style. But interestingly, I found that Sum1 = 233168 and Sum2 = 232169 which is different by 1001. Can anyone please tell me why it's happening? Thank you.
For loop is inclusive, so you get 1000 numbers (0 to 999). Enumerable.Range will give you 999 numbers, because that's what you asked it for passing 999 as second parameter (0 to 998).
999 is the one that makes the difference.
Ok I've found it, my very simple mistake: Enumerable.Range(start,count) which I thought as if it were Enumerable.Range(firstNumber, lastNumber).

Counting occurrences of values in spss

I have 50 variables, named w1 to w50, and each holds a value from 1 to 20. I want to create variables showing the number of occurrences of each of these values. This is what I'd like to do, but SPSS seems to have a problem with me using #n in the COUNT command.
COMPUTE #n = 1 .
DO REPEAT x = num1 to num20 .
COMPUTE x = 0 .
COUNT x = w1 to w50 (#n) .
COMPUTE #n = #n + 1 .
END REPEAT .
This is the error message I get:
Error # 4772 in column 24. Text: #n
On the COUNT command, the parenthesized value list is syntactically invalid.
Execution of this command stops.
You cannot supply a variable as the value list in the COUNT command. Fortunately the work around for your example is quite simple - you can use a stand in increment on the DO REPEAT:
DO REPEAT x = num1 to num20 /#i = 1 to 20.
COUNT x = w1 to w50 (#i).
END REPEAT.
Full example below.
**********************************************.
*creating fake data.
data list free / ID.
begin data
1
2
end data.
vector w(50,F2.0).
loop #i = 1 to 50.
compute w(#i) = TRUNC(RV.UNIFORM(1,21)).
end loop.
vector num(20,F2.0).
execute.
*making new vector.
DO REPEAT x = num1 to num20 /#i = 1 to 20.
COUNT x = w1 to w50 (#i).
END REPEAT.
EXECUTE.
**********************************************.