Expressing relationship between two variables in pseudocode? - java

I have some pseudocode I am trying to analyze:
public static void test(float z) {
float y = 0;
for (float i = 1; i <= z; i++) {
if (y < z) {
y = 4 * i * i + 6;
}
}
return y;
}
From the function, I understand that y = 4i^2 + 6 whenever y < z. However, I am having trouble capturing the relationship between y and z in an equation. I feel that it could be captured as a floor function (step function) -- for a certain range of numbers in z, y will have that specified value.

y becomes greater than z (and stops changing) for the first i such that 2*i^2 + 3 > z. In other words, a minimal i > sqrt((z - 3) / 2), which is floor(sqrt((z - 3)/2)) + 1. Now as you know i, compute y.

Related

Using assignment operator inside of expression

Running this code will return 11 while I was expecting 20. Why is that so?
int x = 1;
int y = x + (x = 10);
System.out.println(y);
Evaluation is from left to right. So
int y = x + (x = 10);
is (with x initially 1):
int y = 1 + 10;
Putting the assignment in () doesn't make it come first. It just ensures that it's a valid expression, since y = x + x = 10 would be y = (x + x) = 10 which would require assigning to something (x + x) that wasn't a variable.
If you want 20, put the assignment first:
int y = (x = 10) + x;
Of course, the vast majority of the time, it's best to avoid these kinds of side-effects and assign x a value outside the expression, breaking the expression up if necessary. Assignment-within-expression can be useful sometimes (particularly while ((blah = getNextBlah()) != null) sort of things), but only in limited situations.

Getting stack overflow when trying to have the method repeat when there is an even number inputted

I have this code :
public static int rsnpeasant(int x, int y) {
if ((y & 1) == 0) {
y = y / 2;
x = x * 2;
rsnpeasant(x, y);
} else {
sum = sum + x;
y = y / 2;
y = y - 1 / 2;
x = x * 2;
if (y == 1) {
sum = total;
return total;
} else {
rsnpeasant(x, y);
}
}
total = sum;
return total;
}
The error is happening on the first rsnpeasant(x,y); line in the first if statement. It seems to be forever looping to that line even though it's supposed to go to the else statement if y is odd. If y is divided by 2 it should become odd at some point.
Link is what im trying to code
y=y-1/2...
Order of operations will evaluate the 1/2 and subtract that from y. In integer arithmetic, 1/2 is 0. I think you want y=(y-1)/2.
Your principal problem is that you are trying to divide an int primitive type, if y = 1, dividing that value by 2 will return 0, then you pass it to the method again, it will always be stuck in the first if statement.
You should return a double, float or bigdecimal in your method, and use one of those types for the parameters too.

Curious on what this function is doing

Can someone tell me what is this function doing? I just know that it returns the sum of x + y, but I want to know why. Thanks
public static int f(int x, int y){
while( y > 0){
x = x + 1;
y = y - 1;
}
return x;
}
There are two cases:
First case: y <= 0
Because the while loop is false, it just returns x ("it skips the part")
Second case: y > 0
Because the while loop is true, it returns x + y (x + number of iterations)
The number of iterations is the value of y because with every iteration, y will be decreased by 1 until y = 0.
The loop starts at the value of y, and decrements it on each iteration, stopping when y gets to zero.
For each of these iterations, 1 is added to x. Therefore, for 'unit' of y, a 'unit' is added to x.
Edit As noted in the comments, the function will not return the sum of the two numbers if y is less then zero, since the loop will not execute at all.
Addition can be viewed as a series of increments. That's what this function does. It increments x y times and returns the result which is x + y. It is assumed that y is a natural number.

Recursion and multiplication

Is this possible guys? This is homework I have, and my teacher obviously believes it is, but it seems to me that it's impossible not to use addition or multiplication outside of the short-multiplication method.
Write (and provide a tester for) a recursive algorithm:
int multiply(int x, int y)
to multiply two positive integers together without using the *
operator. Do not just add x to itself y times!!!
(Hint: Write a recursive method that will multiply an integer by a
value in the range 0 .. 10. Then write a second recursive method to
implement the multiplication algorithm you learned to multiply
multi-digit numbers in elementary school.)
My issue is that once you break down any multi digit number and starting adding those together you have to use multiplication of numbers greater than 10, i.e 22 * 6 is 2 * 6 + 20 * 6 ... so am I totally missing something?
EDIT
I guess I should have added this is the code I have,
public int mult(int x, int y){
return x == 0 ? 0 : (mult(x-1, y) + y);
}
which is perfect, but as far as I understand the instructions, that's breaking do not just add x to itself y times. I personally believe it isn't, but my teacher hasn't been very clear, and I'd like to know if there's some other way that I havn't thought of, sorry for the confusion.
Yes, it's possible. Yes, I think you're missing something. Try writing down the steps you'd follow to manually multiply two numbers, the way you learned in elementary school.
Then turn those steps into code.
My interpretation of the assignment is that the teacher would like the student to implement a recursive algorithm to perform Grid method multiplication (the kind we learn in elementary school).
For example, multiplying 34 x 13 would be done like so...
34
* 13
====
12
90
40
+300
====
442
I didn't have easy access to a Java development environment, so I wrote the code in C# but the algorithm should be simple enough to convert into Java.
public int Multiply(int x, int y)
{
if (x < 0) throw new ArgumentException("must be positive integer", "x");
if (y < 0) throw new ArgumentException("must be positive integer", "y");
if (x == 0 || y == 0) return 0; // obvious quick-exit condition
// integer division
int xDivBy10 = x / 10;
int yDivBy10 = y / 10;
bool xIsSingleDigit = xDivBy10 == 0;
bool yIsSingleDigit = yDivBy10 == 0;
// base case
if (xIsSingleDigit && yIsSingleDigit)
{
return MultiplySingleDigits(x, y);
}
// otherwise, use grid multiplication recursively
// http://en.wikipedia.org/wiki/Grid_method_multiplication
if (xIsSingleDigit) // y must not be a single digit
{
return (Multiply(x, yDivBy10) * 10) + Multiply(x, y % 10);
}
if (yIsSingleDigit) // x must not be a single digit
{
return (Multiply(xDivBy10, y) * 10) + Multiply(x % 10, y);
}
// else - x and y are both numbers which are not single digits
return (Multiply(x, yDivBy10) * 10) + Multiply(x, y % 10); // the same code as the "if (xIsSingleDigit)" case
}
// technically, this algorith can multiply any positive integers
// but I have restricted it to only single digits as per the assignment's requirements/hint
private int MultiplySingleDigits(int x, int y)
{
if (x < 0 || x > 9) throw new ArgumentException("must be in range 0 - 9 (inclusive)", "x");
if (y < 0 || y > 9) throw new ArgumentException("must be in range 0 - 9 (inclusive)", "y");
if (x == 0 || y == 0) return 0; // base case
return x + MultiplySingleDigits(x, y - 1);
}
NOTES:
This approach still uses the * operator but not for actually multiplying x and y, it is used to increase other sub-products by multiples of 10
Many parts of this code could be simplified/refactored but I specifically left them expanded to make the steps more obvious
Of course you can do it.
First of all, think about the condition. If some number is 0, then the result is? Right.. zero.
So.. You'll have if x is zero or y is zero return 0
Now.. saying X * Y is like saying "X, Y times", which is like writing: X + .... + X (Y times).
So, you'll have something like:
x + multiply(x, y - 1);
You'll have to consider the case in which one of the numbers is negative (But if you understand the basic, I believe you can easily do it).
This solution will work for both when y>=0 and y<0
public int multiply(final int x, final int y) {
if (y != 0 && x != 0) {
if (y > 0) {
return multiply(x, y - 1) + x;
} else {
return multiply(x, y + 1) - x;
}
}
return 0;
}
Easily possible.
int multiply(int x, int y) {
if(y == 0) {
return 0;
}
return x + multiply(x, y - 1);
}
The above fails to take into account the case where y is negative, but you wouldn't want me to do all your work for you . . .
static int Multiply(int x, int y)
{
if (y > 0 && x > 0)
return (x + Multiply(x, y - 1));
if (y < 0 && x > 0)
return -Multiply(x, -y);
if (x < 0 && y > 0)
return -Multiply(-x, y);
if (x < 0 && y < 0)
return Multiply(-x, -y);
return 0;
}

Modular inverse - java coding

Please help. I've been working on this non stop and can't get it right. The issue I'm having is that the output I'm getting for the inverse is always 1.
This is the code that I have (it computes GCD and trying to modify so it also computes a^-1):
import java.util.Scanner;
public class scratchwork
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
long n, a, on, oa;
long gcd = 0;
System.out.println("Please enter your dividend:");
n= keyboard.nextLong();
System.out.println("Please enter your divisor:");
a= keyboard.nextLong();
on= n;
oa= a;
while (a!= 0)
{gcd=a;
a= n% a;
n= gcd;
}
System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);
long vX; vS; vT; vY; q; vR; vZ; m; b;
vX = n; vY=a;
vS = 0; vT = 1; m=0; b=0;
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
if (d>1) System.out.println("Inverse does not exist.");
else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
}
}
The code you've posted does not declare most of the variables it uses and thus dues not compile. Most importantly, the variable v it uses to output the result is neither defined nor assigned to anywhere in the posted code - whatever it contains has nothing to do with the calculation.
Can we see the variables declaration? If you mix integer with double, your numbers can be rounded. Anyway, if you only want the inverse, juste use Math.pow(a, -1);
Also, in the second loop, you never set "a" so it will loop forever:
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
#Justin,
Thanks. I was able to figure out how to print out the variables in each loop. I basically had to put my loop up with the GCD loop...that was it. 2 weeks worth of work and I had just to move where the loop was.
It works! I'm sorry but I'm doing a happy dance over here.
Here's a solution in Python that should be easily translatable into Java:
def euclid(x, y):
"""Given x < y, find a and b such that a * x + b * y = g where, g is the
gcd of x and y. Returns (a,b,g)."""
assert x < y
assert x >= 0
assert y > 0
if x == 0:
# gcd(0,y) = y
return (0, 1, y)
else:
# Write y as y = dx + r
d = y/x
r = y - d*x
# Compute for the simpler problem.
(a, b, g) = euclid(r, x)
# Then ar + bx = g -->
# a(y-dx) + bx = g -->
# ay - adx + bx = g -->
# (b-ad)x + ay = g
return (b-a*d, a, g)
def modinv(x, n):
(a, b, g) = euclid(x%n, n)
assert g == 1
# a * x + b * n = 1 therefore
# a * x = 1 (mod n)
return a%n
It uses the stack, but Euclid's algorithm takes O(log n) steps so you won't have a stack overflow unless your numbers are astronomically high. One could also translate it into a non-recursive version with some effort.

Categories

Resources