I have an assignment in which I need to swap two integers without using third variable.
I'm not sure how to do this. How would I code this?
Yes, it's possible:
Dim var1 = 1
Dim var2 = 2
var1 = var1 + var2
var2 = var1 - var2
var1 = var1 - var2
But why do you need it? The code becomes abstruse.
Lets assume
a = 10;
b = 20;
a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20
Values swapped.
Read up on the "xor swap algorithm."
You can find an answer here:
http://www.java2s.com/Tutorial/VB/0040__Data-Type/Swaptwointegerswithoutusingathird.htm
firstValue = firstValue Xor secondValue
secondValue = firstValue Xor secondValue
firstValue = firstValue Xor secondValue
Dim a As Integer
Dim b As Integer
a= 1
b= 2
a = a Xor b
b = a Xor b
a = a Xor b
To swap two numeric variables do like this
a = a + b;
b = a - b;
a = a - b;
OR
a = a xor b;
b = a xor b;
a = a xor b;
where a and b are variables to be swapped
theoretically 3 ways
a = 4 , b = 5
1. Using XOR
a = a XOR b = 4 XOR 5 = 9
b = a XOR b = 9 XOR 5 = 4
a = a XOR b = 9 XOR 4 = 5
2. Using +,-
a = a+b = 4+5 = 9 // should not overflow
b = a-b = 9-5 = 4
a = a-b = 9-4 = 5
3. Using *,/
a = a*b = 4*5 = 20 // should not overflow
b = a/b = 20/5 = 4 // should not overflow and should not be irrational number
a = a/b = 20/4 = 5 // should not overflow and should not be irrational number
The Xor or a+b algorithms above work and are the best way to do this, but just an example of a weird way to do it. Still not sure why you would want to do this. Just build a function that you supply two values ByRef and have it do the standard swap method.
Dim newList as New List(Of Integer)
newList.Add firstvalue
newList.Add secondValue
newList.Reverse
secondValue = newList.Item(0)
firstValue = newList.Item(1)
Take two text boxes and a command box.In command box type this code.
text1.text=val(text1.text) + val(text2.text)
text2.text=val(text1.text) - val(text2.text)
text1.text=val(text1.text) - val(text2.text)
Check link written for you
Approach#1.
Addition and Subtraction Method
Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;
Problem:
Incorrect result when sum of numbers will exceed the Integer range.
Approach#2.
Multiplication and Division Method
Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;
Problems:
If the value of a*b exceeds the range of integer.
If the value of a or b is zero then it will give wrong results.
Approach#3.
XOR Method
Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;
Best approach to solve this problem without any pitfalls.
Related
I'm writing VB Code and I see a question below
There are three positive integers A, B, C
If A is greater than B, C is equal to A+B
If A is less than or equal to B, then C is equal to A-B.
Please use IF...Then and Select/Switch Case to write a program, both of which are used in this program, and additional variables can be added by yourself.
I would like to ask how to write this question, as far as I know, the answer just need only IF Then or Select Case can be realized?
Dim A As Double = 3
Dim B As Double = 2
Dim C As Double = 1
Dim D As Double = 0
D = A - B
Select Case D
Case D > 0
C = A + B
Case D < 0
C = A - B
End Select
If D > 0 Then
C = A + B
ElseIf D < 0 Then
C = A - B
End If
In the real world you wouldn't need to use both an If/Then statement and a Select/Case statement. Since this appears to be homework, I believe the exercise is to see if you can use both conditional check.
I would setup two functions that accept two arguments (a and b) that return the value of c. In your first function use an If/Then and in your second function use a Select/Case.
E.g.
Private Function IfThenOption(a As Integer, b As Integer) As Integer
Dim c As Integer
If (a > b) Then
c = a + b
ElseIf (a < b) Then
c = a - b
Else
c = a
End If
Return c
End Function
Private Function SelectCaseOption(a As Integer, b As Integer) As Integer
Dim c As Integer
Select Case True
Case a > b
c = a + b
Case a < b
c = a - b
Case Else
c = a
End Select
Return c
End Function
Example: https://dotnetfiddle.net/kwcyWc
For example, if I want to find
1085912312763120759250776993188102125849391224162 = a^9+b^9+c^9+d
the code needs to brings
a=3456
b=78525
c=217423
d=215478
I do not need specific values, only that they comply with the fact that a, b and c have 6 digits at most and d is as small as possible.
Is there a quick way to find it?
I appreciate any help you can give me.
I have tried with nested loops but it is extremely slow and the code gets stuck.
Any help in VB or other code would be appreciated. I think the structure is more important than the language in this case
Imports System.Numerics
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Value As BigInteger = BigInteger.Parse("1085912312763120759250776993188102125849391224162")
Dim powResult As BigInteger
Dim dResult As BigInteger
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer
For i = 1 To 999999
For j = 1 To 999999
For k = 1 To 999999
powResult = BigInteger.Add(BigInteger.Add(BigInteger.Pow(i, 9), BigInteger.Pow(j, 9)), BigInteger.Pow(k, 9))
dResult = BigInteger.Subtract(Value, powResult)
If Len(dResult.ToString) <= 6 Then
a = i
b = j
c = k
d = dResult
RichTextBox1.Text = a & " , " & b & " , " & c & " , " & d
Exit For
Exit For
Exit For
End If
Next
Next
Next
End Sub
End Class
UPDATE
I wrote the code in vb. But with this code, a is correct, b is correct but c is incorrect, and the result is incorrect.
a^9 + b^9 + c^9 + d is a number bigger than the initial value.
The code should brings
a= 217423
b= 78525
c= 3456
d= 215478
Total Value is ok= 1085912312763120759250776993188102125849391224162
but code brings
a= 217423
b= 78525
c= 65957
d= 70333722607339201875244531009974
Total Value is bigger and not equal=1085935936469985777155428248430866412402362281319
Whats i need to change in the code to make c= 3456 and d= 215478?
the code is
Imports System.Numerics
Public Class Form1
Private Function pow9(x As BigInteger) As BigInteger
Dim y As BigInteger
y = x * x ' x^2
y *= y ' x^4
y *= y ' x^8
y *= x ' x^9
Return y
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a, b, c, d, D2, n As BigInteger
Dim aa, bb, cc, dd, ae As BigInteger
D2 = BigInteger.Parse("1085912312763120759250776993188102125849391224162")
'first solution so a is maximal
d = D2
'a = BigIntegerSqrt(D2)
'RichTextBox1.Text = a.ToString
For a = 1 << ((Convert.ToInt32(Math.Ceiling(BigInteger.Log(d, 2))) + 8) / 9) To a > 0 Step -1
If (pow9(a) <= d) Then
d -= pow9(a)
Exit For
End If
Next
For b = 1 << ((Convert.ToInt32(Math.Ceiling(BigInteger.Log(d, 2))) + 8) / 9) To b > 0 Step -1
If (pow9(b) <= d) Then
d -= pow9(b)
Exit For
End If
Next
For c = 1 << ((Convert.ToInt32(Math.Ceiling(BigInteger.Log(d, 2))) + 8) / 9) To c > 0 Step -1
If (pow9(c) <= d) Then
d -= pow9(c)
Exit For
End If
Next
' minimize d
aa = a
bb = b
cc = c
dd = d
If (aa < 10) Then
ae = 0
Else
ae = aa - 10
End If
For a = aa - 1 To a > ae Step -1 'a goes down few iterations
d = D2 - pow9(a)
For n = 1 << ((Convert.ToInt32(Math.Ceiling(BigInteger.Log(d, 2))) + 8) / 9) To b < n 'b goes up
If (pow9(b) >= d) Then
b = b - 1
d -= pow9(b)
Exit For
End If
Next
For c = 1 << ((Convert.ToInt32(Math.Ceiling(BigInteger.Log(d, 2))) + 8) / 9) To c > 0 Step -1 'c must be search fully
If pow9(c) <= d Then
d -= pow9(c)
Exit For
End If
Next
If d < dd Then 'remember better solution
aa = a
bb = b
cc = c
dd = d
End If
If a < ae Then
Exit For
End If
Next
a = aa
b = bb
c = cc
d = dd
' a,b,c,d is the result
RichTextBox1.Text = D2.ToString
Dim Sum As BigInteger
Dim a9 As BigInteger
Dim b9 As BigInteger
Dim c9 As BigInteger
a9 = BigInteger.Pow(a, 9)
b9 = BigInteger.Pow(b, 9)
c9 = BigInteger.Pow(c, 9)
Sum = BigInteger.Add(BigInteger.Add(BigInteger.Add(a9, b9), c9), d)
RichTextBox2.Text = Sum.ToString
Dim Subst As BigInteger
Subst = BigInteger.Subtract(Sum, D2)
RichTextBox3.Text = Subst.ToString
End Sub
End Class
[Update]
The below code is an attempt to solve a problem like OP's, yet I erred in reading it.
The below is for 1085912312763120759250776993188102125849391224162 = a^9+b^9+c^9+d^9+e and to minimize e.
Just became too excite about OP's interesting conundrum and read too quick.
I review this more later.
OP's approach is O(N*N*N*N) - slow
Below is a O(N*N*log(N)) one.
Algorithm
Let N = 1,000,000. (Looks like 250,000 is good enough for OP's sum of 1.0859e48.)
Define 160+ wide integer math routines.
Define type: pow9
int x,y,
int160least_t z
Form array pow9 a[N*N] populated with x, y, x^9 + y^9, for every x,y in the [1...N] range.
Sort array on z.
Cost so far O(N*N*log(N).
For array elements indexed [0... N*N/2] do a binary search for another array element such that the sum is 1085912312763120759250776993188102125849391224162
Sum closest is the answer.
Time: O(N*N*log(N))
Space: O(N*N)
Easy to start with FP math and then later get a better answer with crafter extended integer math.
Try with smaller N and total sum targets to iron out implementation issues.
In case a,b,c,d might be zero I got an Idea for fast and simple solution:
First something better than brute force search of a^9 + d = x so that a is maximal (that ensures minimal d)...
let d = 1085912312763120759250776993188102125849391224162
find max value a such that a^9 <= d
this is simple as we know 9th power will multiply the bitwidth of operand 9 times so the max value can be at most a <= 2^(log2(d)/9) Now just search all numbers from this number down to zero (decrementing) until its 9th power is less or equal to x. This value will be our a.
Its still brute force search however from much better starting point so much less iterations are required.
We also need to update d so let
d = d - a^9
Now just find b,c in the same way (using smaller and smaller remainder d)... these searches are not nested so they are fast ...
b^9 <= d; d-=b^9;
c^9 <= d; c-=b^9;
To improve speed even more you can hardcode the 9th power using power by squaring ...
This will be our initial solution (on mine setup it took ~200ms with 32*8 bits uints) with these results:
x = 1085912312763120759250776993188102125849391224162
1085912312763120759250776993188102125849391224162 (reference)
a = 217425
b = 65957
c = 22886
d = 39113777348346762582909125401671564
Now we want to minimize d so simply decrement a and search b upwards until still a^9 + b^9 <= d is lower. Then search c as before and remember better solution. The a should be search downwards to meet b in the middle but as both a and bhave the same powers only few iterations might suffice (I used 50) from the first solution (but I have no proof of this its just my feeling). But still even if full range is used this has less complexity than yours as I have just 2 nested fors instead of yours 3 and they all are with lower ranges...
Here small working C++ example (sorry do not code in BASIC for decades):
//---------------------------------------------------------------------------
typedef uint<8> bigint;
//---------------------------------------------------------------------------
bigint pow9(bigint &x)
{
bigint y;
y=x*x; // x^2
y*=y; // x^4
y*=y; // x^8
y*=x; // x^9
return y;
}
//---------------------------------------------------------------------------
void compute()
{
bigint a,b,c,d,D,n;
bigint aa,bb,cc,dd,ae;
D="1085912312763120759250776993188102125849391224162";
// first solution so a is maximal
d=D;
for (a=1<<((d.bits()+8)/9);a>0;a--) if (pow9(a)<=d) break; d-=pow9(a);
for (b=1<<((d.bits()+8)/9);b>0;b--) if (pow9(b)<=d) break; d-=pow9(b);
for (c=1<<((d.bits()+8)/9);c>0;c--) if (pow9(c)<=d) break; d-=pow9(c);
// minimize d
aa=a; bb=b; cc=c; dd=d;
if (aa<50) ae=0; else ae=aa-50;
for (a=aa-1;a>ae;a--) // a goes down few iterations
{
d=D-pow9(a);
for (n=1<<((d.bits()+8)/9),b++;b<n;b++) if (pow9(b)>=d) break; b--; d-=pow9(b); // b goes up
for (c=1<<((d.bits()+8)/9);c>0;c--) if (pow9(c)<=d) break; d-=pow9(c); // c must be search fully
if (d<dd) // remember better solution
{
aa=a; bb=b; cc=c; dd=d;
}
}
a=aa; b=bb; c=cc; d=dd; // a,b,c,d is the result
}
//-------------------------------------------------------------------------
The function bits() just returns number of occupied bits (similar to log2 but much faster). Here final results:
x = 1085912312763120759250776993188102125849391224162
1085912312763120759250776993188102125849391224162 (reference)
a = 217423
b = 78525
c = 3456
d = 215478
It took 1689.651 ms ... As you can see this is much faster than yours however I am not sure with the number of search iterations while fine tuning ais OK or it should be scaled by a/b or even full range down to (a+b)/2 which will be much slower than this...
One last thing I did not bound a,b,c to 999999 so if you want it you just add if (a>999999) a=999999; statement after any a=1<<((d.bits()+8)/9)...
[Edit1] adding binary search
Ok now all the full searches for 9th root (except of the fine tunnig of a) can be done with binary search which will improve speed a lot more while ignoring bigint multiplication complexity leads to O(n.log(n)) against your O(n^3)... Here updated code (will full iteration of a while fitting so its safe):
//---------------------------------------------------------------------------
typedef uint<8> bigint;
//---------------------------------------------------------------------------
bigint pow9(bigint &x)
{
bigint y;
y=x*x; // x^2
y*=y; // x^4
y*=y; // x^8
y*=x; // x^9
return y;
}
//---------------------------------------------------------------------------
bigint binsearch_max_pow9(bigint &d) // return biggest x, where x^9 <= d, and lower d by x^9
{ // x = floor(d^(1/9)) , d = remainder
bigint m,x;
for (m=bigint(1)<<((d.bits()+8)/9),x=0;m.isnonzero();m>>=1)
{ x|=m; if (pow9(x)>d) x^=m; }
d-=pow9(x);
return x;
}
//---------------------------------------------------------------------------
void compute()
{
bigint a,b,c,d,D,n;
bigint aa,bb,cc,dd;
D="1085912312763120759250776993188102125849391224162";
// first solution so a is maximal
d=D;
a=binsearch_max_pow9(d);
b=binsearch_max_pow9(d);
c=binsearch_max_pow9(d);
// minimize d
aa=a; bb=b; cc=c; dd=d;
for (a=aa-1;a>=b;a--) // a goes down few iterations
{
d=D-pow9(a);
for (n=1<<((d.bits()+8)/9),b++;b<n;b++) if (pow9(b)>=d) break; b--; d-=pow9(b); // b goes up
c=binsearch_max_pow9(d);
if (d<dd) // remember better solution
{
aa=a; bb=b; cc=c; dd=d;
}
}
a=aa; b=bb; c=cc; d=dd; // a,b,c,d is the result
}
//-------------------------------------------------------------------------
function m.isnonzero() is the same as m!=0 just faster... The results are the same as above code but the time duration is only 821 ms for full iteration of a which would be several thousands seconds with previous code.
I think except using some polynomial discrete math trick I do not know of there is only one more thing to improve and that is to compute consequent pow9 without multiplication which will boost the speed a lot (as bigint multiplication is slowest operation by far) like I did in here:
How to get a square root for 32 bit input in one clock cycle only?
but I am too lazy to derive it...
In the following project euler program #56, Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum?
so I wrote the following code:
Dim num As System.Numerics.BigInteger
Dim s As String
Dim sum As Integer
Dim record As Integer
For a = 2 To 99
For b = 1 To 99
num = a ^ b
s = num.ToString
For i = 0 To s.Length - 1
sum += CInt(s.Substring(i, 1))
Next
sum = 0
Next
Next
The answer I got from the program was not the correct answer, so I wrote the following code so I can see what numbers set a new high value and see if something is wrong.
If sum > record Then
record = sum
Console.WriteLine(a & "," & b)
End If
One of the answers was a=10 b= 81. Obviously that doesn't make sense, because that value is 1 + 81 "0" = 1, but watching the result of 10^81, was 999999999999999921281879895665782741935503249059183851809998224123064148429897728
I searched about the accuracy of BigInteger but couldn't find anything, is there something that I'm missing?
I have a sequence of numbers as follows:
1 , 1, 5, 13, 41, 121, 365, ....
The first two values are:
N(1) = 1 and N(2) = 1
As from 3rd value, N(i) = 2*N(i-1) + 3*N(i-2)
The issue I am facing with is: If I give an argument of p, it should return me the last values of the sequence < p (Using fortran77).
For instance, if p = 90, it should return the value 41.
a = 1
b = 1
while b < p:
c = 2 * b + 3 * a
a = b
b = c
return a
The Fortran equivalent is:
function fct(p) result(a)
integer, intent(in) :: p
integer :: a, b, c
a = 1
b = 1
do while (b < p)
c = 2 * b + 3 * a
a = b
b = c
enddo
end function
program test
integer :: fct
external fct
print *,fct(90)
end program
Assuming you already have the sequence in a variable lst, and p set,
max(filter(lambda x:x<=p, lst))
def get_last_element(p):
n1 = 1
n2 = 1
while True:
if n2 > p:
return n1
n1, n2 = n2, 2*n2 + 3 * n1
print(get_last_element(90))
I wrote a piece of code in Fortran 2003. I defined a type which has memory for two last parts of the sequence.The procedure is a recursive function. The type can be used standalone to get n-th part of the sequence or efficiently placed in a loop to find parts in a row (not necessarily beginning at 1) as it has memory of previous parts. (compiler: gfortran 4.8).
The type is defined in mymod.f90 file as
module mymod
implicit none
type seq_t
integer :: saved_i = 0, saved_val_i = 0, saved_val_i_1 = 0
contains
procedure :: getpart => getpart_seq
end type
contains
recursive function getpart_seq(this,i) result(r)
class(seq_t) :: this
integer, intent(in) :: i
integer :: r,r_1,r_2
if (i.eq.1.or.i.eq.2) then
r = 1
elseif(i.eq.this%saved_i) then
r = this%saved_val_i
elseif(i.eq.this%saved_i-1) then
r = this%saved_val_i_1
else
r_1 = this%getpart(i-1)
r_2 = this%getpart(i-2)
r = 2*r_1 + 3*r_2
this%saved_val_i_1 = r_1
end if
this%saved_i = i
this%saved_val_i = r
end function getpart_seq
end module mymod
The main program for the requested case is
program main
use mymod
implicit none
type (seq_t) :: seq
integer :: i,p,tmp_new,tmp_old,ans
! Set the threshold here
p = 90
! loop over parts of the sequence
i = 0
do
i = i + 1
tmp_new = seq%getpart(i)
print*,tmp_new
if (tmp_new>p) then
ans = tmp_old
exit
end if
tmp_old = tmp_new
end do
print*,"The last part of sequence less then",p," is equal to",ans
end program
The outcome is
1
1
5
13
41
121
The last part of sequence less then 90 is equal to 41.
I tried to google the answer for this but could not find it. I am working on VB.Net. I would like to know what does the operator += mean in VB.Net ?
It means that you want to add the value to the existing value of the variable. So, for instance:
Dim x As Integer = 1
x += 2 ' x now equals 3
In other words, it would be the same as doing this:
Dim x As Integer = 1
x = x + 2 ' x now equals 3
For future reference, you can see the complete list of VB.NET operators on the MSDN.
a += b
is equivalent to
a = a + b
In other words, it adds to the current value.
It is plus equals. What it does is take the same variable, adds it with the right hand number (using the + operator), and then assigns it back to the variable. For example,
Dim a As Integer
Dim x As Integer
x = 1
a = 1
x += 2
a = a + 2
if x = a then
MsgBox("This will print!")
endif
those 2 lines compiled produce the same IL code:
x += 1
and
x = x + 1
Just makes code more efficient -
Dim x as integer = 3
x += 1
'x = 4
is the same as
x = x + 1
'x = 4
It can also be used with a (-):
x -= 1
' x = 2
Is the same as
x = x - 1
'x = 2