I'm creating a method to add up all numbers between two integers.
I currently have:
/**
* Add up all numbers between two integers
*/
public void Sum(int a,int b)
{
int result = 0;
while (a <=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
This only works if a <= b. How do i also do it for if a > b ?
I have to use a while loop
The easiest way to do this is to reuse what you already have. Let's rename your method first:
public void sumMonotonic(int a, int b)
{
int result = 0;
while (a <=b) {
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
So sumMonotonic() only works if its first argument is no bigger than its second. But now we can define sum() like this:
public void sum(int a, int b)
{
if (a<=b)
sumMonotonic(a,b);
else
sumMonotonic(b,a);
}
This just invokes the other function with the arguments in the appropriate order.
Actually there's one other oddity that we might fix. It seems a little unidiomatic to have a sumMonotonic() method that does the printing. It would be better if it returned the sum, and if the sum() method did the printing. So we'd refactor it like this:
public int sumMonotonic(int a, int b)
{
int result = 0;
while (a <=b) {
result+=a;
a++;
}
return result;
}
public void sum(int a, int b)
{
int result;
if (a<=b)
result = sumMonotonic(a,b);
else
result = sumMonotonic(b,a);
System.out.println("The sum of all numbers is "+result);
}
public void Sum(int a,int b)
{
int result = 0;
if(a>b) //swap them
{
result=a;
a=b;
b=result;
result=0;
}
while (a <=b) {
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
Related
I am trying to find the position of the maximum of three numbers that the user inputs. I do not know how to find the position of this but I can find max of the numbers.
Here is the task:
Here is the method named getNumberOfMaxParam that takes three integer numbers and returns the position of the first maximum in the order of the method parameters.
UPDATE: I am trying to compare the int a.b.c but I get This method must return a result of type int error
Code:
import java.util.Scanner;
class App {
public static int getNumberOfMaxParam(int a, int b, int c) {
int firstMax = Math.max(a, b);
int highMax = Math.max(firstMax, c);
if (a == highMax) {
System.out.println("1");
} else if (b == highMax) {
System.out.println("2");
} else if (c == highMax) {
System.out.println("3");
} else {
return highMax;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final int a = scanner.nextInt();
final int b = scanner.nextInt();
final int c = scanner.nextInt();
System.out.print(getNumberOfMaxParam(a, b, c));
}
}
Now how do I find the position?
You can do this with the Stream api. You simply pass an array of values in the order you want. Then create an IntStream of the values and find the max. Then create an IntStream of the indices and find the first value in the array to see if it matches max, and return the index.
private static int getIndexOfMax(int... values) {
int max = IntStream.of(values).max().orElseThrow(IllegalStateException::new);
return IntStream.range(0, values.length)
.filter(index -> values[index] == max)
.findFirst().orElseThrow(IllegalStateException::new);
}
int index = getIndexOfMax(1, 2, 3);
assert index == 2;
**PS. It could be controversial if you supply same value for multiple inputs.**
public static int getNumberOfMaxParam(int a, int b, int c) {
int firstMax = Math.max(a, b);
int highMax = Math.max(firstMax, c);
return (highMax == a ? 1 : (highMax == b ? 2 : 3 );
}
I want to ask a question how to create a "Division" function which contains variable number of parameters in Java? Just Like As I did for sum method:
public static int sum(int ... x)
{
int sum=0;
for(int i : x)
{
sum=sum+i;
}
return sum;
}
Well, the difference is that you're gonna have to provide a number to divide as parameter:
public static int div(int div, int ... x)
{
for(int i : x)
{
if(i > 0) div=div/i;
}
return div;
}
Be careful to test if i is greater than 0, otherwise the compiler will throw an error, since you cannot divide by 0.
I did the following to calculate recursive logarithm:(b is the base of log here)
int log(int b, int n) {
if (n/b == 1) {
return 1;
} else {
return log(b, n/b) + 1;
}
}
However, it's wrong.I'm doing it from the openDSA interactive platform.The original question is the following:
For function "log", write the missing base case condition and the recursive call. This function computes the log of "n" to the base "b". As an example: log 8 to the base 2 equals 3 since 8 = 222. We can find this by dividing 8 by 2 until we reach 1, and we count the number of divisions we made. You should assume that "n" is exactly "b" to some integer power.
int log(int b, int n) {
if /* Missing base case condition */ {
return 1;
} else {
return /* Missing a Recursive case action */;
}
}
My code is incorrect.I'm getting infinite recursion.
If the format MUST be like this:
int log(int b, int n ) {
if <<enter base case>> {
return 1;
} else {
return <<enter action case>> ;
}
}
Then the safest method (that I can come up with) would be:
int log(int b, int n ) {
if (n <= b) {
return 1;
} else {
return log(b, n/b)+1 ;
}
}
A better solution in my opinion would be
int log(int b, int n ) {
if (b > n) {
return 0;
} else {
return 1 + log(b, n/b);
}
}
This returns the log base b of n rounded down to an integer, and has more consistency with inexact results than the other answer.
e.g. log(2,6)=2 ; log(2,7)=2 ; log(2,8)=3 ; log(2,9)=3
Though, it still doesn't handle things like b < 2 or cases where the result would be negative.
int log(int b, int n ) {
if (b == 1) {
return b;
} else if (n == 1) {
return 0;
} else {
return 1 + log(b, n/b);
}
}
I'm working on this simple java recursion problem given the following directions:
Calculate the golden ratio.
Given two numbers a and b with a > b > 0, the ratio is b / a.
I have done some code but I'm stuck on getting the recursion working properly. Here's my code:
public class MyTesting {
public static void main(String[] args) {
System.out.println(ratio(8 , 4));
}
public static double ratio(int a, int b) {
int goldelRatio = 0;
if(a > b && b > 0){
return goldelRatio = a / b;
}
return goldelRatio;
}
}
How about something like this:
double goldenRatio(double a, double b, double epsilon) {
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b, epsilon);
}
}
This way you achieve what you need in one function, with epsilon deciding how fine the resolution would be.
Also as an added bonus, and although Java doesn't have (at the time of writing this at least) tail recursion optimization, in theory this function could be optimized by tail recursion.
example with hard coded epsilon:
double goldenRatio(double a, double b) {
double epsilon = 0.00001;
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b);
}
}
example run:
public static void main(String[] args) {
double goldenRation1 = goldenRatio(1.0, 1.0);
System.out.println(goldenRation1); // prints 1.618032786885246
System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true
double goldenRation2 = goldenRatio(100.0, 6.0);
System.out.println(goldenRation2); // prints 1.6180367504835589
System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true
}
Yours is not a recursive function, a recursive function that calculates Golden Ratio would look like the one below.
private int MAX_COUNTER = 50;
private int count = 0;
public double ratio(double a, double b) {
count++;
double goldenRatio = b / a;
if (count < MAX_COUNTER) {
return ratio(b, a + b);
}
return goldenRatio;
}
NOTE: I put the counters because given that is a recursive function trying to find a number with infinite decimals, it will cause the JVM to go on StackOverflow :) , so we got to stop it sooner or later.
Recursion mainly means methods calling themself, meaning you should try something like that:
public double recursionMethod(int a, int b){
int c = a+b;
if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42)
return ratio(c,b);
else
return recursionMethod(b,c);
}
1/42 is just your accuracy, you can implement any other breaking condition you like. Call this method in main with arguments (1,1).
I have created a class named Times and I have to construct 4 overloaded methods. I just would like some help understanding overloaded methods and at least maybe some help with the first one. I would really appreciate it. Thanks :)
multiply 2 integers and return the (integer) product
multiply 3 integers and return the (integer) product
multiply 2 double values and return the (double) product
multiply 3 double values and return the (double) product
like this?
public class Times {
public static int multiply(int a, int b) {
return a * b;
}
public static int multiply(int a, int b, in c) {
return multiply(a, b) * c;
}
public static double multiply(double a, double b) {
return a * b;
}
public static double multiply(double a, double b) {
return multiply(a, b) * c;
}
}
"Overloaded methods" just means the methods would all have the same name (and be in the same class). The parameters need to be different either in number or type, however.
Since the all multiply stuff, "multiply" makes sense as a name.
The first one:
multiply 2 integers and return the
(integer) product
So it returns an integer (an int), is named "multiply", takes 2 ints as parameters, that gives us:
int multiply(int a, int b) {
It returns the product, so the body is:
return a * b;
And then we're done with that one:
}
That gives us:
int multiply(int a, int b) {
return a * b;
}
Use the same approach and the same name for the others.
it would look somthing like this :
public class Times {
public int mult(int a, int b) {
return a*b;
}
public int mult(int a, int b, int c) {
return a*b*c;
}
//2 more overloaded versions to come here
}
as for understanding what they mean - when your code is compiled the compiler determines which of the methods (all called the same name) to use by looking at the arguments.
so for instance for something like this
int a = 1;
int b = 1;
Times t = new Times();
t.mult(a,b);
the compiler will pick the 1st of the 2 mult methods i demonstrated, while for this:
int a = 1;
int b = 1;
int c = 2;
Times t = new Times();
t.mult(a,b,c);
it will pick the 2nd (based on the number of arguments)
You can do something like this
public class Times {
public static void main(String[] args) {
System.out.println(multiplyInt(1,2));
System.out.println(multiplyDoubles(2.0,3.0));
}
public static int multiplyInt(int... numbers){
int multiply = 1;
for(int number : numbers ){
multiply = multiply*number;
}
return multiply;
}
public static double multiplyDoubles(double... numbers){
double multiply = 1;
for(double number : numbers ){
multiply = multiply*number;
}
return multiply;
}
}