Can I extend the program’s functionality to additionally tell the user the smallest number, by creating a separate method, smaller, in a similar fashion to the larger method?
public static void main(String[] args)
{
System.out.println("Please enter two numbers");
Scanner scan = new Scanner(System.in);
int first = scan.nextInt();
int second = scan.nextInt();
System.out.println("The largest "+larger(first, second));
}// end of main
public static double larger(double x, double y)
{
if (x >= y)
return x;
return y;
} //end of larger
This is trivial, e.g. (keeping the same code conventions)
public static double smaller(double x, double y)
{
if (x >= y)
return y;
return x;
} //end of larger
The above is not optimal, but it aligns with the existing code.
You can also use Math.min(double a, double b), or ternary operator: a < b ? a : b.
P.S. One number is not greater than another if they are equal.
Related
I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I must calculate X to the power of Y with recursion and only addition. I really can't figure out how to do it without using loops or using multiplication. This is not my homework. It is a question from last years exams I am stuck on.
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println(findXY(x, y, 0));
}
static int findXY(int x, int y, int result){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return result+x;
}
result+=x;
return findXY(x, y-1, result);
}
}
First two ifs look fine, maybe the 'y-1' as well but after that it might be incorrect, also is there a chance not to use 'int result' but only to pass x and y to the function?
Since we cannot using multiplication, we need to use recursive addition. check my code below. Your first 3 if conditions are correct. Modify the later code to below method.
package com.java;
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println("Final :: " + findXPowerY(x, y));
sc.close();
}
static int findXPowerY(int x, int y) {
if (y == 0) {
return 1;
}
if (x == 0) {
return 0;
}
if (y == 1) {
return x;
}
return multiply(x, findXPowerY(x, y - 1));
}
static int multiply(int x, int y) {
if (y != 0)
return (x + multiply(x, y - 1));
else
return 0;
}
}
What your findXY method really does is simple multiplication, not exponentiation. First of all, it could be improved from using 3 parameters to only 2:
static int findXY(int x, int y){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return x;
}
return x + findXY(x, y-1);
}
Secondly, you are halfway done! You just found a way to multiply with only using addition and recursion. What you now need to do, is call this multiplication certain numer of times, again, using recursion.
Before we start, let's rename the method from findXY to multiply, since it better indicates its intent and functionality.
Thirdly, we need to implement the method that calculates the power. Keeping in mind that we renamed your findXY method to multiply and changed the number of parameters from 3 to 2, our implementation might look like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return x * power(x, y-1));
}
Hey, but we are not allowed to use multiplication! Fortunately, we made our own implementation! The final product looks like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return multiply(x, power(x, y-1));
}
Please do note that this approach does not work with negative numbers. If they are the case, you could wrap this method in another one that simply calls power with abs value and inverts the result
My assignment is to write a recursive function to multiply two numbers together, using only an addition function, ++, and --. My addition function is:
public static int peanoplus(int x, int y) {
if(y==0) return x;
else return peanoplus(++x,--y);
}
What I have so far for my multiplication function is:
public static int peanotimes(int x, int y)
{
if(y==0) return x;
else return peanotimes(peanoplus(x,x),--y);
}
I am not exactly sure what to put in the first parameter for the peanotimes function. Right now the issue is that I'm doubling the number, rather than adding it to the original number. I know that I need to maintain the x variable so that the recursive calls can continue adding the original number (instead of doubling every time), but then where would I actually add the numbers?
I found this which is very similar to my question, but even with those tips I am unable to find a solution.
if( y == 0 || x == 0 ) { return 0; }
else { return peanoplus(x, peanotimes(x,--y)); }
This version closest matches the formal Peano axiom of x * S(y) = x + (x * y)
public static int peanotimes(int x, int y)
{
if (y == 0) {
return 0; // terminate recursion, NB: not "x"
} else {
return peanoplus(x, peanotimes(x, --y));
}
}
Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
Addition information:
Chip doesn't support multiplication, only addition. I should work around this problem by creating a recursive method, mult(), that performs multiplication
of x and y by adding x to itself y times. Its arguments are x and y and its return
value is the product of x and y. I should then write the method and a main() to
call it.
It's pure logical thinking, but I get lost every time I try to think what to do.
I am stuck at the math part..
What I have, that doesn't work and I know the math is wrong, but I am not good at this:
public static void mult(int x, int y) {
x = 0;
y = 0;
if (y > 0) {
for (int i = 0; i < y; i++) {
x = x * (x * y);
return mult(x, y);
}
}
}
When I hear "recursion", I expect to see two things:
A function calling itself with modified arguments each time.
A stopping condition right at the top that tells the function when to stop, avoiding an infinite stack.
So where are yours? Start with writing those down in words before you write code.
One possibility is to use an accumulator which will store the current value of the multiplication. I replace missing statements by ??? :
public static void main(String []args){
System.out.println(mult(2,5));
}
public static int mult(int x, int y) {
if(???) return ???;
else return multAcc(???,???,???);
}
private static int multAcc(int x, int y, int acc){
if(???) return ???;
else return multAcc(???, ???, ???);
}
... by adding x to itself y times.
You could actually do that, instead of multiplying. Oh, and maybe if you don't set both x and y to zero, you would have something to add ;-)
One last thing: If you want a recursive solution, you don't need the for-loop.
Java has no TCO by design, so using recursion for linear (not tree-like) processes is very bad idea. Especially for such task, which will most likely become a bottleneck in your program. Use loop instead.
Oh, it must be recursive anyway? Looks like a homework task. Do it yourself then.
All you need to remember is that a multiplication is a repeated addition (assuming that both operands are >= 0), so we have:
The base case is when y is zero
If y is not zero, then add x one more time, and subtract 1 from y
Notice that as long as y is positive, it'll eventually have a value of zero. So basically we keep adding x a total number of y times; this is what I mean:
public static int mult(int x, int y) {
if (y == 0)
return 0;
return x + mult(x, y-1);
}
The same code can be written in a tail-recursive style, too - meaning: there's nothing to do after the recursive call returns, and this is important for certain languages that support a so-called tail-call optimization:
public static int mult(int x, int y, int accumulator) {
if (y == 0)
return accumulator;
return mult(x, y-1, x + accumulator);
}
The above will get called as follows, noticing that the last parameter is always initialized in zero:
mult(10, 5, 0)
=> 50
public static int mult(int x, int y) {
if (y == 0) {
return 0;
}
if (y > 0) {
return x + mult(x, y - 1);
} else {
return -x + mult(x, y + 1);
}
}
this was the solution by the way