This question already has answers here:
Calculate the power of any exponent (negative or positive)
(5 answers)
Closed 9 years ago.
I need to write a method named pow2 that accepts a real number base and an integer exponent as parameters. It should return the base raised to the given power. Your code should work for both positive and negative exponents. For example, the call pow2(2.0, -2) returns 0.25. Do not use Math.pow in your solution.
This is what I have so far:
public double pow2(double x,int y){
double total=1;
for(int i=1;i<=y;i++){
total*=x;
}
return total;
}
But the problem is when I try to call pow(2.0, -2), it returns me 1.0 instead. How do I implement this method?
You have to branch, depending if you have a negative or a positive value.
Here a version that works with recursion:
public double pow2(double x,int y){
return _pow2(1.0, x, y);
}
private double _pow2(double res, double x, int y) {
if (y < 0) return _pow2(res/x, x, y+1);
if (y > 0) return _pow2(res*x, x, y-1);
return res;
}
If y is too big or too small, then you'll run into a stack overflow, so changing it to a non-recursive function is left to the op.
Edit: about your last question, you set the result to 1.0, the body of the loop is never used because !(1 <= -2), so you return the unmodified result of 1.0
Well, finally if you want to do it in an iterative way, just check first if y is positive or negative.
public double pow2(double x, int y)
{
double total = 1.0;
if(y > 0)
{
for(int i = 1 ; i <= y ; i++)
{
total *= x;
}
}
else
{
for(int i = -1 ; i >= y ; i--)
{
total /= x;
}
}
return total;
}
public static void main(String[] args) {
System.out.println(pow2(2,3));
}
public static double pow2(double x,int y){
double total=1;
for(int i=1;i<=y;i++){
total*=x;
}
return total ;
}
public static double pow2(double x,int y){
double total=1;
if(y>0){
for(int i=1;i<=y;i++){
total*=x;
}
return total;
}
else if (y<0){
double temp=1/x;//this makes 2 as 1/2
y=y*-1; //to have a meaningful iteration if for loop
for(int i=1;i<=y;i++){
total*=temp;
}
return total;
}else
return 1;
}
Related
I am trying Leetcode Question - 69. Sqrt(x)
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
class Solution {
public int mySqrt(int x) {
int ans = 0;
int i=1;
while(i*i<=x){
ans = i;
i++;
}
return ans;
}
}
This is the code I came up with. But the testcase input=2147395600 is not passing.
My Output = 289398
Expected Output = 46340
I'm confused as I have put the condition i*i<=x, then how can ans be more than the sqrt value?
Since you are comparing i * i with the input x, if the input x is too close to Integer.MAX_VALUE (2.147.483.647), like in that test case, i * i will be bigger than the maximum value allowed for an int to have and i*i<=x will be true.
Possible solutions:
Implement a binary search algorithm where max would be the floor(sqrt(Integer.MAX_VALUE)) or 46340.
Implement a algorithm where ans, i and x are declared locally as long type variables and in the return line you return the value cast to int using return (int)ans;
By running the following algorithm you can see the limit of a java int exploding and what happens afterwards.
int x = 2;
while(true) {
System.out.println(x);
x *= 2;
}
Not pretending to be fast, just the idea that (n+1)2=n2 + 2n + 1:
public static int mySqrt(int x) {
int i = 0;
while (x >= 0) {
x -= (i++ << 1) + 1;
}
return i - 1;
}
My JavaScript Solution
var mySqrt = function(x) {
var ans = 1;
if(x === 0){
ans = 0;
} else {
for (let i = 1; i< x;i++){
if(i*i === x){
ans = i;
break;
}
if(i*i >x){
ans = i - 1;
break;
}
}
}
return ans;
};
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 6 years ago.
Improve this question
I know what coupling and cohesion mean.
I have got the following example and it has some maintainability issues and therefore it needs some refactoring:
The problem is, I could not relate any coupling, cohesion or any other maintainability issue other than GLOBAL VARIABLES. How can I refactor the following code without this global variables issue (because global variables increase complexity & increases the code inflexibility?!)
double value;
double min, max;
public void read()
{
do
{
value = ConsoleInput.readDouble();
}
while(value < min || value > max);
}
public double hyp()
{
double x, y;
min = 0.0;
max = 100.0;
read();
x = value;
read();
y = value;
return Math.sqrt(x * x + y * y);
}
I was thinking it to refactor like below:
public void read()
{
double value;
double min = 0.0;
double max = 100.0;
do
{
value = ConsoleInput.readDouble();
}
while(value < min || value > max);
}
public double hyp()
{
double x, y;
read();
x = value;
read();
y = value;
return Math.sqrt(x * x + y * y);
}
Does this look right? Or is there any other efficient way of refactoring this?
Refactor your read() method like this:
public double read(double min, double max)
So rather than saving the value in a global, you return it from the function
Having "global variables" like min and max is absolutely fine, if they are "global" only inside its own class - thats the way the class variables are supposed to be used.
However "read" value should return value, not insert it into some class variable and then use. Also it would be nice to create instance of class with min and max in constructor for maximum flexibility, but also having default constructor.
public class GoodApp {
private double min, max;
public GoodApp(double min, double max){
this.min = min;
this.max = max;
}
public GoodApp(){
this(1,100);
}
public double read() {
double value;
do {
value = ConsoleInput.readDouble();
} while (value < min || value > max);
return value;
}
public double hyp() {
double x, y;
x = read();
y = read();
return Math.sqrt(x * x + y * y);
}
}
Based on the information you provided, I would suggest the following:
public double read() {
// set value to a not accepted value to start the while-loop
double value = -1;
double min = 0.0;
double max = 100.0;
while(value < min || value > max) {
value = ConsoleInput.readDouble();
}
return value;
}
public double hyp() {
double x = read();
double y = read();
return Math.sqrt(x * x + y * y);
}
Here is my version.
Few points to keep in mind - A method should expose its dependencies properly (What it depends on - like dependency injection), otherwise it can be a liar.
Also, your read method is not making use of the state of current object (i.e. it is not employing this reference). So, it can be static (but that makes unit testing tough - if it is a concern for you).
So, I would suggest the following (This may seem to be overkill for this small program - but good in real time projects. It reduces coupling because you can push any implementation of ReadData) -
enum Bound{
MAX(100.0), MIN(0.0);
public double value(){
return this.value;
}
private final double value;
private Bound(double value){
this.value = value;
}
}
public class CalcHyp{
ReadData readData;
CalcHyp(ReadData readData){
this.readData = readData;
}
public double hyp() {
double x = readData.read();
double y = readData.read();
return Math.sqrt(x * x + y * y);
}
public static void main(String[] args) {
CalcHyp calcHyp = new CalcHyp(new ReadData());//Declare the dependencies.(Dependency Injection)
System.out.println(calcHyp.hyp());
}
}
class ReadData{ //Can declare an interface in real time, and various implementations based on your requirement.
double read() {
double value = Bound.MAX.value()+1;
while(value < Bound.MIN.value() || value > Bound.MAX.value()) {
value = ConsoleInput.readDouble();
}
return value;
}
}
public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
This is an exercise in the book I am stumped on. Why would the program not just recurse until the two numbers are equal and then return n ? Also, where it says,
int result = n * recurse;
How does it multiply int n by recurse which would be (int, int)? How can it multiply one integer by a set of two integers?
In what way am I misunderstanding this program?
EDIT: This is a different question because I am not using factorials
prod(x,y) is equivalent to y! when x=1.
If x is different from 1, then its doing recursive multiplication (y * (y- 1) * (y -2) .... ) until y = x.
Assuming y > x.
By the way, if x > y then prod() will crash.
I've having some trouble with recursion. At the moment, this code gives me an error message "missing return statement". Any way to get this working the way I want it to? I want it to calculate for xn and then return "count" when n reaches zero.
public class Question6p2 {
public static void main(String[] args){
int n = -6;
int x = 2;
int count = x;
power2(n, x, count);
System.out.println(power2(n, x, count));
}
public static int power2(int n, int x, int count){
if (n != 0){
if (n>0){
count = count * x;
n = n - 1;
}
else if (n<0) {
count = count * -x;
n = n + 1;
}
power2(n, x, count);
}
else if (n == 0){
return count;
}
}
}
Maybe I'm coming about this all wrong. Anyone care to help?
Currently, you have this statement:
power2(n, x, count);
... which ignores the result completely. In that branch, we never return anything from the method call. I suspect these two issues are linked.
I suspect you just want:
return power2(n, x, count);
Currently you are getting an error about not having a return statement because your return statement is within an if statement, so if that if statement doesn't run you will not return anything which is a problem.
Also I think you are going about recursion fundamentally wrong, as you are never calling back to your method recursively.
What you probably want to do within your power method is to accept n as the number of time to call your method, then lower it by 1 with each recursion. Then on every recursion multiply x by the original value.
Here is what I mean:
public static double power2(int n, int x,int xOriginal){
if(n == 0){
return 1;
}
if(n < 0){
return 1 / power2(n*-1, x, x);
}
if(n <= 1){
return x;
}
return power2(n -1, x * xOriginal, xOriginal);
}
Edit: Works with negative n now.
There are a few things wrong with your algorithm:
What does it mean to have a negative exponent?
You should understand that x-n can be written 1 / xn. This is not what was reflected in your algorithm.
All possible cases
There are 4 basic cases when calculating exponents.
There is any value x0 = 1.
Any x1 = x
Any negative exponent x-n = 1 / xn
Any positive exponent greater than one: xn where n > 1
Your algorithm should return 1 when x has an exponent of zero. Return x when the exponent is 1 or recursively call the algorithm when n > 1.
In the special case where n < 0 (ie you have a negative exponent) You can simply return the reciprocal 1 / method() as long as you change the sign of n before calling the method.
The line:
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
Checks for negative exponents, and returns 1 / xn Take note that the sign of n changed here, and now this is operating like any other method call with positive exponents.
public class TestCode {
public static void main(String[] args){
int n = 4;
int x = 5;
double count = x;
System.out.println(power2(n, x, count));
}
public static double power2(int n, int x, double count){
if (n == 0)
return 1;
else{
if (n > 1){
count = count * x;
n = n - 1;
}
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
else if (n == 1) {
return count;
}
return power2(n, x, count);
}
}
}
I'm having difficulty writing a program to solve this exercise from a Java text book:
Write a method raiseRealToPower that takes a floating-point value x and an integer
k and returns xk. Implement your method so that it can correctly calculate the result
when k is negative, using the relationship
x^(-k) = 1 / x^k.
Use your method to display a table of values of πk for all values of k from –4 to 4.
I didn't done this part with PI, i know that, if my programs starts to work... this is what i done... tell me please, what is wrong.
import acm.program.*;
public class vjezba55 extends ConsoleProgram {
private static final double PI = 3.14159253;
public void run() {
double x = readDouble ("x: ");
double k = readDouble ("k: ");
println ("x^k = " + raiseDoublePower(x,k));
}
/* Method that counts x^k */
private double raiseDoublePower (double x, double k){
if (k >= 0) {
return Math.pow(x, k);
}
else {
double total = 1;
for (int i= 0; i>k; i--) {
total = (double) 1 / x;
}
return total;
}
}
}
Take a look at your loop code. You are just recalculating total from scratch on each iteration, rather than updating the previous result.
I don't understand the part in the question regarding PI, but your method may be much simpler (according to using the relationship x^(-k) = 1 / x^k):
private double raiseDoublePower (double x, double k){
if (k >= 0) {
return Math.pow(x, k);
}
else {
return 1 / Math.pow(x, -k);
}
}