I have two classes: Fraction and Test. I already do well with class Fraction, but class Test has some issues.
I want to allow the user enter the fractions and store in ArrayList, the user can compare two fraction from the array by choosing the index of the array. But when I compare two fraction, it doesn't work well!
class Fraction:
class Fraction {
private int numerator;
private int denominator;
Fraction(int n, int d) {
numerator = n;
denominator = d;
}
public Fraction(int n) {
this(n, 1);
}
public Fraction() {
numerator = 0;
denominator = 1;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public void display() {
String s = this.getNumerator() + "/" + this.getDenominator();
System.out.println(s);
}
public double evaluate() {
double n = numerator;
double d = denominator;
return (n / d);
}
public boolean isEquals(Fraction f){
int gcd1 = gcd(f.getNumerator(), f.getDenominator());
double fractionFloatValue = (f.getNumerator()/gcd1) / (f.getDenominator()/gcd1);
int gcd2 = gcd(this.getNumerator(), this.getDenominator());
double fractionFloatValue2 = (this.getNumerator()/gcd2) / (this.getDenominator()/gcd2);
return (fractionFloatValue == fractionFloatValue2) ? true : false;
}
public Fraction add(Fraction f2) {
Fraction r = new Fraction((numerator * f2.denominator)
+ (f2.numerator * denominator), (denominator * f2.denominator));
return r;
}
static private int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static String asFraction(int x, int y) {
int gcd = gcd(x, y);
return (x / gcd) + "/" + (y / gcd);
}
/*public static void main(String[] argv) {
Fraction f0 = new Fraction();
Fraction f1 = new Fraction(3);
Fraction f2 = new Fraction(20, 60);
Fraction f3 = new Fraction(1, 3);
System.out.println("--------------Testing constructors--------------");
f0.display();
f1.display();
f2.display();
System.out.println("--------------Test if two fractions is equal--------------");
System.out.println(f2.isEquals(f1));
}*/
}
and class Test:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void enterFraction(){
ArrayList<Fraction> arr = new ArrayList<Fraction>();
Scanner scanner = new Scanner(System.in);
boolean check = false;
int i = 1;
while(!check){
System.out.println("Enter fraction"+i+":");
Fraction f = new Fraction();
System.out.println("Enter Numerator: ");
int numerator = scanner.nextInt();
scanner.nextLine();
f.setNumerator(numerator);
System.out.println("Enter Denominator: ");
int denominator = scanner.nextInt();
scanner.nextLine();
f.setDenominator(denominator);
System.out.println("Your fraction"+i+" is: "+f.getNumerator()+"/"+f.getDenominator());
arr.add(f);
System.out.println("Want to compare fractions? (Y/Yes or N/No)");
String compareRequest = scanner.nextLine();
if(compareRequest.equalsIgnoreCase("y")){
System.out.println("Choose your target fraction!!! (enter the index of the array)");
int position = scanner.nextInt();
scanner.nextLine();
Fraction targetFraction = arr.get(position);
targetFraction.display();
System.out.println("Choose your second fraction to compare!!! (enter the index of the array)");
int position2 = scanner.nextInt();
scanner.nextLine();
Fraction secondFraction = arr.get(position2);
secondFraction.display();
boolean compareTwoFractions = secondFraction.isEquals(targetFraction);
if(compareTwoFractions == true){
System.out.println("Two fractions are equal");
}
else if(compareTwoFractions == false){
System.out.println("Two fractions are not equal");
}
}
i++;
System.out.println("Do you want to enter more fraction? (Y/Yes or N/No)");
String checkRequest = scanner.nextLine();
if(checkRequest.equalsIgnoreCase("n")){
check = true;
}
}
}
public static void main(String[] args){
enterFraction();
}
}
I input like this:
Enter fraction1:
Enter Numerator:
2
Enter Denominator:
4
Your fraction1 is: 2/4
Want to compare fractions? (Y/Yes or N/No)
n
Do you want to enter more fraction? (Y/Yes or N/No)
y
Enter fraction2:
Enter Numerator:
1
Enter Denominator:
3
Your fraction2 is: 1/3
Want to compare fractions? (Y/Yes or N/No)
y
Choose your target fraction!!! (enter the index of the array)
0
2/4
Choose your second fraction to compare!!! (enter the index of the array)
1
1/3
Two fractions are equal
Do you want to enter more fraction? (Y/Yes or N/No)
You see it not work, 2/4 == 1/3. Please point me somethings with this.
The problem is that getNumerator(), getDenominator(), and gcd return an int. Therefore, the division inside your equals method is done in integers:
double fractionFloatValue = (f.getNumerator()/gcd1) / (f.getDenominator()/gcd1);
...
double fractionFloatValue2 = (this.getNumerator()/gcd2) / (this.getDenominator()/gcd2);
The value of fractionFloatValue and fractionFloatValue2 are, in fact, integers, even though they are assigned to variables of type double. Both 1/3 and 1/2 are proper fractions, so integer division evaluates to zero in both cases. That's why your equals returns true in both cases.
There are two ways to fix this:
Declare gcd1 and gcd2 as double. This would force the division into double; unfortunately, your code would suffer from double comparison for equality, which is inherently imprecise, or
Use identity n1/d1 == n2/d2 when n1*d2 == n2*d1. This eliminates division, so you get perfect precision in your comparisons until you overflow (and you would not overflow with the constraints that you are using if you use long for the results of your multiplication).
I change two line that #dasblinkenlight has mentioned by:
double fractionFloatValue = ((f.getNumerator()/gcd1)*1.0) / (f.getDenominator()/gcd1);
double fractionFloatValue2 = ((this.getNumerator()/gcd2)*1.0) / (this.getDenominator()/gcd2);
and It worked now.
Related
excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
import java.math.BigInteger;
public class Rational {
// Data fields for numerator and denominator
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
/** Construct a rational with default properties */
public Rational() {
this(BigInteger.ZERO, BigInteger.ONE);
}
/** Construct a rational with specified numerator and denominator */
public Rational(BigInteger numerator, BigInteger denominator) {
BigInteger gcd=new BigInteger(String.valueOf(gcd(numerator,
denominator)));
BigInteger r1=new
BigInteger(String.valueOf(denominator.compareTo(BigInteger.ZERO)));
this.numerator = (r1.multiply(numerator)).divide(gcd);
this.denominator = (denominator.abs()).divide(gcd);
}
/** Find GCD of two numbers */
private static long gcd(BigInteger n, BigInteger d) {
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
int gcd = 1;
for (int k = 1; (new BigInteger(String.valueOf(k))).compareTo(n1)<=0 &&
(new BigInteger(String.valueOf(k))).compareTo(n2)<=0; k++) {
if (n1.mod(new BigInteger(String.valueOf(k))).equals(BigInteger.ZERO) &&
n2.mod(new BigInteger(String.valueOf(k))).equals(BigInteger.ZERO))
gcd = k;
}
return gcd;
}
/** Return numerator */
public BigInteger getNumerator() {
return numerator;
}
/** Return denominator */
public BigInteger getDenominator() {
return denominator;
}
/** Add a rational number to this rational */
public Rational add(Rational secondRational) {
BigInteger n =
numerator.multiply(secondRational.getDenominator())
.add(denominator.multiply(sec
ondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Subtract a rational number from this rational */
public Rational subtract(Rational secondRational) {
BigInteger n =
(numerator.multiply(secondRational.getDenominator()))
.subtract(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Multiply a rational number to this rational */
public Rational multiply(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getNumerator());
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Divide a rational number from this rational */
public Rational divide(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator());
BigInteger d = denominator.multiply(secondRational.numerator);
return new Rational(n, d);
}
/** Compute the square of this rational number*/
public Rational square() {
BigInteger n = numerator.multiply(numerator);
BigInteger d = denominator.multiply(denominator);
return new Rational(n, d);
}
/** toString */
public String toString() {
return numerator + "/" + denominator;
}
}
and this is the testRational class
import java.math.BigInteger;
public class TestRational {
public static void main(String[]args){
int y = 1;
BigInteger i=new BigInteger(String.valueOf(1));
BigInteger a=new BigInteger(String.valueOf(2));
BigInteger b=new BigInteger(String.valueOf(3));
BigInteger c=new BigInteger(String.valueOf(5));
Rational sum = new Rational(BigInteger.ZERO,a);
Rational r0 = new Rational(b,b.add(i));
Rational r2 = new Rational(a,c);
Rational r3 = new Rational(a,c);
Rational s1 = r3.multiply(r2);
Rational s2 = r3.square();
Rational s3 = r2.divide(r3);
Rational r1 = new Rational(i,a);
do{
sum = sum.add(r0);
b = b.add(a);
y++;
}while(y<49);
System.out.println(sum.multiply(sum));
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(r0);
}
}
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
Let's write it less confusingly, without all the unnecessary stuff and confusing loop. The definition of the sum is (1/2 + 3/4 ... 99/100) so let's start by creating all the fractions in the sum:
for (int i = 1; i <= 99; i += 2) {
BigRational t = new BigRational(BigInteger.valueOf(i), BigInteger.valueOf(i + 1));
}
They have to be summed, so there has to be a variable declared outside the loop to sum up all those fractions into:
Rational sum = new Rational();
for (int i = 1; i <= 99; i += 2) {
Rational t = new Rational(BigInteger.valueOf(i), BigInteger.valueOf(i + 1));
sum = sum.add(t);
}
Then square that and you have your answer. I get:
87593039510089573189394173247956745677798336081
-----------------------------------------------
38416307357189261992010230523038591203840000
Which I can't verify but it looks reasonable enough. The expected answer is "a bit less than 502" (because it's the square of 50 terms that are nearly 1, if 0.5 can be called that) and this is close enough.
By the way, stop using String.valueOf everywhere in Rational. Just work with numbers. And BigInteger already implements gcd, you don't have to write your own (less efficient) version. I had to replace this otherwise it took too long.
It's not clear what your sequence of numbers is, but I will go with the following assumption:
If your goal is the simply return the value of (1/2 + 3/4 + 5/6 + ... + 97/98 + 99/100) ^ 2. Then I would suggest the following:
//This method will return the value of (1/2 + 3/4 + 5/6 + ... + 97/98 + 99/100) ^ 2
public int calc(){
double denominator = 2;
double numerator = denominator - 1; //in your sequence, numerator is always 1 less than denominator
double sum = 0;
while(denominator <= 100){
sum = sum + (numerator / denominator); //shorthand sum += (numerator / denominator);
denominator = denominator + 2; //shorthand denominator += 2;
numerator = denominator - 1;
}
return sum * sum; //this is equivalent to sum ^ 2
}
I was trying to get a cubic root in java using Math.pow(n, 1.0/3) but because it divides doubles, it doesn't return the exact answer. For example, with 125, this gives 4.9999999999. Is there a work-around for this? I know there is a cubic root function but I'd like to fix this so I can calculate higher roots.
I would not like to round because I want to know whether a number has an integer root by doing something like this: Math.pow(n, 1.0 / 3) % ((int) Math.pow(n, 1.0 / 3)).
Since it is not possible to have arbitrary-precision calculus with double, you have three choices:
Define a precision for which you decide whether a double value is an integer or not.
Test whether the rounded value of the double you have is a correct result.
Do calculus on a BigDecimal object, which supports arbitrary-precision double values.
Option 1
private static boolean isNthRoot(int value, int n, double precision) {
double a = Math.pow(value, 1.0 / n);
return Math.abs(a - Math.round(a)) < precision; // if a and round(a) are "close enough" then we're good
}
The problem with this approach is how to define "close enough". This is a subjective question and it depends on your requirements.
Option 2
private static boolean isNthRoot(int value, int n) {
double a = Math.pow(value, 1.0 / n);
return Math.pow(Math.round(a), n) == value;
}
The advantage of this method is that there is no need to define a precision. However, we need to perform another pow operation so this will affect performance.
Option 3
There is no built-in method to calculate a double power of a BigDecimal. This question will give you insight on how to do it.
The Math.round function will round to the nearest long value that can be stored to a double. You could compare the 2 results to see if the number has an integer cubic root.
double dres = Math.pow(125, 1.0 / 3.0);
double ires = Math.round(dres);
double diff = Math.abs(dres - ires);
if (diff < Math.ulp(10.0)) {
// has cubic root
}
If that's inadequate you can try implementing this algorithm and stop early if the result doesn't seem to be an integer.
I wrote this method to compute floor(x^(1/n)) where x is a non-negative BigInteger and n is a positive integer. It was a while ago now so I can't explain why it works, but I'm reasonably confident that when I wrote it I was happy that it's guaranteed to give the correct answer reasonably quickly.
To see if x is an exact n-th power you can check if the result raised to the power n gives you exactly x back again.
public static BigInteger floorOfNthRoot(BigInteger x, int n) {
int sign = x.signum();
if (n <= 0 || (sign < 0))
throw new IllegalArgumentException();
if (sign == 0)
return BigInteger.ZERO;
if (n == 1)
return x;
BigInteger a;
BigInteger bigN = BigInteger.valueOf(n);
BigInteger bigNMinusOne = BigInteger.valueOf(n - 1);
BigInteger b = BigInteger.ZERO.setBit(1 + x.bitLength() / n);
do {
a = b;
b = a.multiply(bigNMinusOne).add(x.divide(a.pow(n - 1))).divide(bigN);
} while (b.compareTo(a) == -1);
return a;
}
To use it:
System.out.println(floorOfNthRoot(new BigInteger("125"), 3));
Edit
Having read the comments above I now remember that this is the Newton-Raphson method for n-th roots. The Newton-Raphson method has quadratic convergence (which in everyday language means it's fast). You can try it on numbers which have dozens of digits and you should get the answer in a fraction of a second.
You can adapt the method to work with other number types, but double and BigDecimal are in my view not suited for this kind of thing.
You can use some tricks come from mathematics field, to havemore accuracy.
Like this one x^(1/n) = e^(lnx/n).
Check the implementation here:
https://www.baeldung.com/java-nth-root
Here is the solution without using Java's Math.pow function.
It will give you nearly nth root
public class NthRoot {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int testcases = scanner.nextInt();
while (testcases-- > 0) {
int root = scanner.nextInt();
int number = scanner.nextInt();
double rootValue = compute(number, root) * 1000.0 / 1000.0;
System.out.println((int) rootValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static double compute(int number, int root) {
double xPre = Math.random() % 10;
double error = 0.0000001;
double delX = 2147483647;
double current = 0.0;
while (delX > error) {
current = ((root - 1.0) * xPre + (double) number / Math.pow(xPre, root - 1)) / (double) root;
delX = Math.abs(current - xPre);
xPre = current;
}
return current;
}
I'd go for implementing my own function to do this, possibly based on this method.
Well this is a good option to choose in this situation.
You can rely on this-
System.out.println(" ");
System.out.println(" Enter a base and then nth root");
while(true)
{
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
double negodd=-(Math.pow((Math.abs(a)),(1.0/b)));
double poseve=Math.pow(a,(1.0/b));
double posodd=Math.pow(a,(1.0/b));
if(a<0 && b%2==0)
{
String io="\u03AF";
double negeve=Math.pow((Math.abs(a)),(1.0/b));
System.out.println(" Root is imaginary and value= "+negeve+" "+io);
}
else if(a<0 && b%2==1)
System.out.println(" Value= "+negodd);
else if(a>0 && b%2==0)
System.out.println(" Value= "+poseve);
else if(a>0 && b%2==1)
System.out.println(" Value= "+posodd);
System.out.println(" ");
System.out.print(" Enter '0' to come back or press any number to continue- ");
con=Integer.parseInt(br.readLine());
if(con==0)
break;
else
{
System.out.println(" Enter a base and then nth root");
continue;
}
}
It's a pretty ugly hack, but you could reach a few of them through indenting.
System.out.println(Math.sqrt(Math.sqrt(256)));
System.out.println(Math.pow(4, 4));
System.out.println(Math.pow(4, 9));
System.out.println(Math.cbrt(Math.cbrt(262144)));
Result:
4.0
256.0
262144.0
4.0
Which will give you every n^3th cube and every n^2th root.
Find nth root Using binary search method.
Here is the way to find nth root with any precision according to your requirements.
import java.util.Scanner;
public class FindRoot {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int testCase = scanner.nextInt();
while (testCase-- > 0) {
double number = scanner.nextDouble();
int root = scanner.nextInt();
double precision = scanner.nextDouble();
double result = findRoot(number, root, precision);
System.out.println(result);
}
}
}
private static double findRoot(double number, int root, double precision) {
double start = 0;
double end = number / 2;
double mid = end;
while (true) {
if (precision >= diff(number, mid, root)) {
return mid;
}
if (pow(mid, root) > number) {
end = mid;
} else {
start = mid;
}
mid = (start + end) / 2;
}
}
private static double diff(double number, double mid, int n) {
double power = pow(mid, n);
return number > power ? number - power : power - number;
}
private static double pow(double number, int pow) {
double result = number;
while (pow-- > 1) {
result *= number;
}
return result;
}
}
I'm using this nth_root algorithm, which also provide the remainder :
public static BigInteger[] sqrt(final BigInteger n) {
final BigInteger[] res = {ZERO, n,};
BigInteger a, b;
assert (n.signum() > 0);
a = ONE.shiftLeft(n.bitLength() & ~1);
while (!a.equals(ZERO)) {
b = res[0].add(a);
res[0] = res[0].shiftRight(1);
if (res[1].compareTo(b) >= 0) {
res[1] = res[1].subtract(b);
res[0] = res[0].add(a);
}
a = a.shiftRight(2);
}
return res;
}
public static BigInteger[] nth_root(BigInteger n, final int nth) {
final BigInteger[] res;
switch(nth){
case 0 : res = new BigInteger[]{n.equals(ONE) ? ONE : ZERO, ZERO} ; break;
case 1 : res = new BigInteger[]{n, ZERO}; break;
case 2 : res = sqrt(n); break;
default:
int sign = n.signum() ;
n = n.abs();
res = new BigInteger[]{n.shiftLeft((n.bitLength() + nth - 1) / nth), n};
while(res[1].compareTo(res[0])<0) {
res[0] = res[1];
res[1] = BigInteger.valueOf(nth-1).multiply(res[1]).add(n.divide(res[1].pow(nth - 1))).divide(BigInteger.valueOf(nth));
}
res[1] = res[0].pow(nth);
res[1] = n.subtract(res[1]);
if (sign < 0 && (nth & 1) == 1) {
res[0] = res[0].negate();
res[1] = res[1].negate();
} else assert (sign > 0);
}
return res ;
}
}
I think my program is skipping my while loop, but I'm honestly not sure exactly what is happening. The function is supposed to reduce fractions by finding the GCD and then dividing numerator and denominator by that number.
class Rational {
private int numerator, denominator;
//Constructor
public Rational (int num, int den) {
numerator = num;
denominator = den;
}
//Method for multiplying fractions
public Rational times (Rational that) {
Rational x = new Rational (this.numerator*that.numerator, this.denominator*that.denominator);
x = x.reduce();
return x;
}
//Method for displaying fractions as strings
public String toString() {
return new String(numerator+"/"+denominator);
}
//Method for adding fractions
public Rational plus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)+(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for subtracting fractions
public Rational minus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)-(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for dividing fractions
public Rational divideBy(Rational that) {
Rational x = new Rational (this.numerator*that.denominator, this.denominator*that.numerator);
//x = x.reduce();
return x;
}
public Rational reduce() {
int a = Math.abs(this.numerator);
int b = Math.abs(this.denominator);
int c = Math.min(a, b);
System.out.println(c);
System.out.println(a%c);
System.out.println(b%c);
if (a==0) {
return new Rational (0,1);
}
else {
while (((a%c)!= 0) && ((b%c)!= 0)) {
c = c-1;
System.out.println(c);
}
System.out.println(c);
return new Rational (this.numerator/c,this.denominator/c);
}
}
}
public class RationalTester {
public static void main(String[] args) {
Rational x = new Rational (6,4); //The fraction 6/4
Rational y = new Rational (5,2); //The fraction 5/2
Rational z = x.times(y); //Their product
Rational w = x.plus(y); //Their sum
Rational v = x.minus(y); //Their difference
Rational u = x.divideBy(y); //Their quotient
JOptionPane.showMessageDialog(null, x.toString()+" * "+y.toString()+" = "+z.toString());
JOptionPane.showMessageDialog(null, x.toString()+" + "+y.toString()+" = "+w.toString());
JOptionPane.showMessageDialog(null, x.toString()+" - "+y.toString()+" = "+v.toString());
JOptionPane.showMessageDialog(null, x.toString()+" / "+y.toString()+" = "+u.toString());
}
}
I'm getting the absolute value of the numerator and denominator to ensure that if the fraction is negative I'll be keeping that at the end. If the numerator is 0, I was asked to return (0,1). The question is about the while loop... it seems that it's being skipped completely. Any suggestions?
Because always its condition is false.
In the first lines you set c equal to either a or b. So there are two possibilities:
If c == a, then a%c will be zero. So the while condition is false.
If c == b, then b%c will be zero. So the while condition is false.
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);
}