how to convert decimal value in to a Fraction value? - java

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;
}
}

Related

java.lang.StringIndexOutOfBoundsException on repeating decimal to fraction calculator

I'm new to java and I'm trying to code a method that takes a repeating decimal and turns it into a fraction. It takes input like (double decimal without repeating, int number of trailing digits to repeat) i.e. (0.3,1) would be 0.3333.... and (1.583,2) would be 1.5838383....
I am getting this error and I can't seem to find out what the problem is. The current input is (10.3,1)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at Fraction.<init>(Fraction.java:44)
at Main.main(Main.java:12)
exited with non-zero status
Heres my code:
public Fraction(double t, int repeating)
{
double decRight = t, decLeft = t;
String rStr = "0000000000000000000" + String.valueOf(decRight);
String lStr = "0000000000000000000" + String.valueOf(decLeft);
int count1 = 0, count2 = 0, rDecIndex = rStr.indexOf("."), lDecIndex = lStr.indexOf(".");
while(!lStr.substring(lDecIndex - repeating,lDecIndex).replace("\\.","").equals(lStr)) //this is line 44, the problem area
{
decLeft *= 10;
count1++;
lStr = "0000000000000000000" + String.valueOf(decLeft);
lDecIndex = lStr.indexOf(".");
}
while(!rStr.substring(rDecIndex,repeating).replace("\\.","").equals(rStr))
{
decRight*= 10;
count2++;
rStr = "0000000000000000000" + String.valueOf(decRight);
rDecIndex = rStr.indexOf(".");
}
top = (int)(decLeft - decRight);
bot = (int)(Math.pow(10,count1) - Math.pow(10,count2));
reduce();
}
The error is in the substring.
Based on the comment, you want an integer with the repeating decimal in it and an integer with what is before the repeating part.
I think you've gone about this the hard way rather than just using substring to get the parts of the string that you want.
/**
* Code By Loren CC-BY
*/
public class test
{
public static void fraction(String t, int repeating)
{
int bot = 0;
for (int i = 0; i < repeating; i++) {
bot *= 10;
bot += 9;
}
String dString = t;
// Get the repeating part of the string as an int
int repeat = Integer.valueOf(dString.substring(dString.length()-repeating));
// Get the string from in front of the repeating number
String front = dString.substring(0, dString.length()-repeating);
// Convert it to a double
double before = Double.valueOf(front);
// Debugging information
System.out.println("Before: "+ front+" " +before+" "+dString.substring(dString.length()-repeating));
// Turn the before string into an int and compute the denominator such that 1.5 could become 15/10
int count = 0;
while (Math.abs(Math.round(before) - before) > 0.000001) {
before *= 10;
count++;
}
// Print debugging information
System.out.println(count);
// Compute the top of the combined fraction
int top = ((int)before)*bot+repeat;
bot = (int)Math.pow(10,count) * bot;
System.out.println(top+" "+bot);
// TODO: Reduce fraction
}
public static void main(String[] args) {
fraction("0.3",1);
fraction("1.580",2);
fraction("0.34",1);
fraction("0.34",2);
}
}
Note: You can't pass in the double 1.580 because that as a string is 1.58 not 1.580 as the 0 is omitted which messes up the function.
For Converting repeating decimals to fractions could you try the following:
import java.math.BigInteger;
public class ConvertRepeatingNumbersToFraction {
public static void main(String[] args) {
convertToFraction("0.3",1);
convertToFraction("1.580",2);
convertToFraction("0.16",1);
convertToFraction("0.34",2);
convertToFraction("0.42",2);
convertToFraction("0.34",1);
}
private static void convertToFraction(String x, int numOfRepeatingDigits) {
int denominator = 0;
for (int i = 0; i < numOfRepeatingDigits; i++) {
denominator = denominator * 10 + 9;
}
int repeatingNumber = Integer.valueOf(x.substring(x.length() - numOfRepeatingDigits));
double numerator = Double.valueOf(x.substring(0, x.length() - numOfRepeatingDigits));
int count = 0;
if (numerator % 1 != 0) {
numerator = numerator * 10;
count++;
}
numerator = numerator * denominator + repeatingNumber;
denominator = (int) Math.pow(10, count) * denominator;
int[] fraction = reduce((int)numerator, denominator);
System.out.println(fraction[0] + "/" + fraction[1]);
}
private static int[] reduce(int num, int den) {
// common divisor
int commonDivisor = BigInteger.valueOf(num).gcd(BigInteger.valueOf(den)).intValue();
return new int[]{ num / commonDivisor, den / commonDivisor };
}
}
I have checked the test numbers on http://onlinecalculators.brainmeasures.com/Numbers/RecurringDecimalNumbertoFraction.aspx and the result are the same.
Hope that helps :)

Converting decimal to binary (Java)

I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number < 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
// convert to binary by successively dividing by larger factors of 2
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
if (number / factorOfTwo >= 1) {
System.out.print("1");
number -= factorOfTwo;
} else
System.out.print("0");
}
} // end of main
}// end of class
You have a problem that you are writing the number backwards. You need to start with the highest bit first
for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {
When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1
You could take the easy way out and use:
Integer.toBinaryString(int i) then print the string to the console.
Check it out here.
public class DCTB {
public void convertor(int n)
{
for(int i=0;i<10;i++)
{
int arr=(int) (n%2);
n=n/2;
System.out.println(Integer.toString(arr));
}
}
public static void main(String args[])
{
DCTB obj=new DCTB();
obj.convertor(10);
}
}

Issue with compare two fractions

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.

Binary to decimal in java using only recursion (no loops)

I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?
This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer and size : ");
input = scan.nextInt();
size = scan.nextInt();
System.out.println(binaryToDecimal(input, size));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
}
public static int binaryToDecimal(int binary, int size) {
if (binary == 0) {
return 0;
}
return binary % 10
* (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);
}
}
Here is an improved version
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer : ");
int input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
String binInput = scan.next();
System.out.println(binaryToDecimal(binInput));
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
public static int binaryToDecimal(String binInput){
int len = binInput.length();
if (len == 0) return 0;
String now = binInput.substring(0,1);
String later = binInput.substring(1);
return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);
}
}
Don't parse binary in reverse order.
Here by calling binaryToDecimal(int) it will return decimal number.
public static int binaryToDecimal(int binary) {
return binaryToDecimal(binary, 0);
}
public static int binaryToDecimal(int binary, int k) {
if (binary == 0) {
return 0;
}
return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}
If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2). Here you will have to pass binary number in the form of String.
If you are looking to do this using a String to hold the binary representation, you could use the following:
public static int binaryToDecimal(String binaryString) {
int size = binaryString.length();
if (size == 1) {
return Integer.parseInt(binaryString);
} else {
return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1 in binary is 1 in decimal, so it would return 1. That is what
if (size == 1) {
return Integer.parseInt(binaryString);
}
Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size) and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1). The call made in the return statement to
binaryString.substring(1, size)
Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001, on the first loop it would chop the first 1 off and call the function again with 1001. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.
Integer.parseInt(binaryString.substring(0, 1))
Gets the first number in the current string, and
* (int) Math.pow(2, size - 1)
is saying Multiple that by 2 to the power of x, where x is the position that the number is in. So again with our example of 11001, the first number 1 is in position 4 in the binary representation, so it is adding 1 * 2^4 to the running total.
If you need a method to test this, I verified it working with a simple main method:
public static void main(String args[]) {
String binValue = "11001";
System.out.println(binaryToDecimal(binValue));
}
Hopefully this makes sense to you. Feel free to ask questions if you need more help.
Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.
static int pow = 0;
public static int binaryToDecimal(int binary) {
if (binary <= 1) {
int tmp = pow;
pow = 0;
return binary * (int) Math.pow(2, tmp);
} else {
return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
}
}
Note: the reason, why I introduce pow, is that static field needs to be reset.
Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
input = scan.nextInt();
System.out.println(binaryToDecimal(input));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
return -1;
}
public static int binaryToDecimal(int binary) {
if(binary==0)
{
return 0;
}
else
{
String n=Integer.toString(binary);
int size=(n.length())-1;
int k=(binary%10)*(int)(Math.pow(2,size));
return k + binaryToDecimal(((int)binary/10));
}
}
}

Does Java have an exponential operator?

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);
}

Categories