recursion - how to get a whole number without decimal - java

import java.util.*;
// Algorithm and Java program to find a Factorial of a number using recursion
public class factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number: ");
int n = input.nextInt();
System.out.println("The factorial of " + n + " is " + factorial(n));
}
private static double factorial (int n)
{
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
}
Please enter a number:
8
The factorial of 8 is 40320.0
Process finished with exit code 0
How to get a whole number without decimal?

You can get the int Value or Double Value by calling:
Double n = new Double(40320.99);
int i = n.intValue();
You can directly print the result whatever it's int or Double Value data type.

Replace
System.out.println("The factorial of " + n + " is " + factorial(n));
by
System.out.println("The factorial of " + n + " is " + (int) factorial(n));
OR (better way)
Replace
private static double factorial (int n)
by
private static int factorial(int n)
Explanation
Since your method is returning a double, you need to convert it to an int, which does not have decimal places. You might want to look at methods of the Math class like round(), floor(), etc.

Related

Why does this java code to count digit of floating value goes in loop for this value?

import java.util.Scanner;
class FloatDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
int x = (int) n;
int count = 0;
do {
count++;
x = x / 10;
} while (x != 0);
System.out.println("Before Decimal Digits: " + count);
//it gets stuck from here only
do {
count++;
n = n * 10;
} while (n != (int) n);
System.out.println(count + " total digits present in there in number.");
}
}
This goes in an infinite loop for the value: 58.2354/58.234. It is working fine with other values too and longer values too.
If some debug logging is added to the second loop, it can be seen, that when multiplying a double number by 10, there is a tiny error which does not allow the comparison n == (int) n ever become true.
It is actually a known issue that floating-point arithmetics has a certain computation error, so it should be taken into account when comparing the double n to its counterpart with the decimal point shifted right:
do {
count++;
n = n * 10;
System.out.println(count + " - " + n);
} while (Math.abs(n - (int) n) > 1E-7);
System.out.println(count + " total digits present in the number.");
Output:
58.234
Before Decimal Digits: 2
3 - 582.34
4 - 5823.400000000001
5 - 58234.00000000001
5 total digits present in the number.

Java - Recursion Program - way to convert an inputted base to base 10 on a given number

I am given a non-recursive method, that I need to modify to make recursive.
This is what I have so far:
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
BigInteger answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
static BigInteger basen(int number, int base ) {
List<Integer> remainder = new ArrayList<>();
int count = 0;
String result = "";
while( number != 0 ) {
remainder.add( count, number % base != 0 ? number % base : 0 );
number /= base;
try {
result += remainder.get( count );
} catch( NumberFormatException e ) {
e.printStackTrace();
}
}
return new BigInteger( new StringBuffer( result ).reverse().toString() );
}
}
It's converting it to base 10 then the given base. I need it to convert to the given base first then base 10.
UPDATE:
I changed around Caetano's code a bit and think I am closer.
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int resultC;
String resultD;
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
if (newNumber == 0)
resultC = Integer.parseInt(result);
resultD = Integer.toString(resultC);
return resultD;
Now when I compile it it gives me an error it says:
BaseN.java:49: error: variable resultC might not have been initialized
resultD = Integer.toString(resultC);
Am I on the right track here? Any help is appreciated
Its hard to tell what you are asking for.
I can only assume that you want to convert from a given base to base 10. The way that you would do this is explained in this page here: MathBits introduction to base 10.
The way explained in this is simple. For each digit in the number you get the base to the power of the position of the digit(reversed) and multiply that by whatever the digit is. Then add all the results. So 237 in base 8 would be
(8^2 * 2) + (8^1 * 3) + (8^0 * 7) = 159
Now you will run in to a problem when you do this with bases higher then 10 since the general notation for digits above 9 is alphabetical letters. However you could get around this by having a list of values such as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F] and compare the digits with this list and get the index of the location of that digit as the number.
I hope this is what you were asking for.
Now then this is code that does what you want it to do. Get a number in a given base and convert it to base 10. However I don't see why you need to use a recursive method for this. If this is some kind of school task or project then please tell us the details because I don't personally see a reason to use recursion. However the fact that your question asks us to modify the code up top to make it recursive then it makes much more sense. Since that code can be edited to be as such.
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
String number = input.next();
int base = input.nextInt();
int answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
private static int basen(String number, int base ) {
int result = 0;
for(int i = 0; i < number.length(); i++) {
int num = Integer.parseInt(number.substring(i, i + 1));
result += Math.pow(base, number.length() - i - 1) * num;
}
return result;
}
However what I think that you want is actually this which shows recursion but instead of converting from base given to base 10 it converts from base 10 to base given. Which is exactly what the code you showed does but uses recursion. Which means '512 6' will output '2212'
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
String answer = new StringBuffer(basen(number, base)).reverse().toString();
System.out.println(number + " base-" + base + " = " + answer);
}
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
return result;
}
I figured out a way to do it recursively. Thank you everyone who provided help. I ended up using Math.pow on the base and put the length of the number -1 for how it would be exponentially increased. Math.pow puts the result in double format so I just converted it back to an int. My professor gave me 100% for this answer, so I'd imagine it would work for others too.
public static int basen(int number, int base) {
String numberStr;
int numberL;
char one;
String remainder;
int oneInt;
int remainderInt;
double power;
int powerInt;
numberStr = Integer.toString(number);
numberL = numberStr.length();
if(numberL > 1){
one = numberStr.charAt(0);
remainder = numberStr.substring(1);
oneInt = Character.getNumericValue(one);
remainderInt = Integer.parseInt(remainder);
power = Math.pow(base, (numberL - 1));
powerInt = (int)power;
return ((oneInt * powerInt) + (basen(remainderInt, base)));
}
else{
return number;
}
}

Fraction-decimal(and vice versa) converter

I have 2 parts of code, the first one being converting fraction to decimal, and the second one being converting decimal to fraction.
However, I have to combine the two piece of code together and I have no idea.I want it to detect the input as either doubles or fraction and convert it to the other.
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
public class Fractions {
public static void main(String args[]) {
double decimal;
double originalDecimal;
int LIMIT = 12;
int denominators[] = new int[LIMIT + 1];
int numerator, denominator, temp;
int MAX_GOODNESS = 100;
// Get a number to be converted to a fraction
if (args.length == 1) {
decimal = Double.valueOf(args[0]).doubleValue();
} else {
// No number was given, so just use pi
assert args.length == 0;
decimal = Math.PI;
}
originalDecimal = decimal;
// Display the header information
System.out.println("-------------------------------------------------------");
System.out.println("Program by David Matuszek");
System.out.println("Input decimal number to be converted: " + decimal);
System.out.println();
// Compute all the denominators
System.out.println("All computed denominators:");
int i = 0;
while (i < LIMIT + 1) {
denominators[i] = (int)decimal;
System.out.print(denominators[i] + " ");
decimal = 1.0 / (decimal - denominators[i]);
i = i + 1;
}
System.out.println();
System.out.println();
// Compute the i-th approximation
int last = 0;
while (last < LIMIT) {
// Print out the denominators used in this computation
System.out.print("Using these " + (last + 1) + " denominators: ");
for (int j = 0; j <= last; j++) {
System.out.print(denominators[j] + " ");
}
System.out.println();
// Initialize variables used in computation
numerator = 1;
denominator = 1;
temp = 0;
// Do the computation
int current = last;
while (current >= 0) {
denominator = numerator;
numerator = (numerator * denominators[current]) + temp;
temp = denominator;
current = current - 1;
}
last = last + 1;
// Display results
double value = (double)numerator/denominator;
int goodness = denominators[last];
double error = 100 * Math.abs(value - originalDecimal) / originalDecimal;
System.out.print("fraction = " + (int)numerator + "/" +
(int)denominator);
System.out.print(", value = " + value);
System.out.print(", goodness = " + goodness);
System.out.println(", error = " + (int)error + "%");
System.out.println();
// Exit early if we have reached our goodness criterion
if (Math.abs(goodness) > MAX_GOODNESS) break;
}
}
}
If I was doing it all on one prompt, I would make two static methods Fraction.TryParse(), and I would use the built in Double.TryParse(), if decimal.TryParse returns true then you do in fact have a decimal. If it returns false, then you have a Fraction, therefore you have to use the same string you passed into Decimal.TryParse() in Fraction.TryParse(). Of course you will need some sanity checks in your Fraction.TryParse() method. The prompt could look something like this:
Enter Decimal/Fraction: 3.14
Enter Decimal/Fraction: 1 + 1/2
Enter Decimal/Fraction: 1 1/2
Enter Decimal/Fraction: 1 (1/2)
You see, if you want this all on one line you need some way to be able to delimit the characters, like a space, or brackets, or simply a + sign which would be mathematically accurate. If it is all on one line it also simplifies your program a little bit because you don't have multiple prompts for one object. The "1 (1/2)" input is not technically mathematically accurate, but you can kind of see how the data is supposed to be structured, you just can't be mathematically rigid with that prompt.
Here I am using the fraction one and one half, your implementation doesn't have a mixed number implementation, but you could just input 1/2 or something, just regular fractions.

Recursion - Java

I am working on a program where I have to use recursion to calculate the sum of 1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1). However, I am not sure how to make my program show the term that must be added in order to reach the number enter by the user. For example. If I enter 12, I want to know how many terms of the series [1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1)] were added to get approximately to the number 12.
What I don't want to get is the sum of inputting 12 which in this case is 5.034490247342584 rather I want to get the term that if I were to sum all numbers up to that term I would get something close to 12.
Any help will be greatly appreciated!
This is my code
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
System.out.println(sum(number) + " is the term that should be added in order to reach " + number);
}
public static double sum(double k) {
if (k == 1)
return 1/3;
else
return ((k/(2*k+1))+ sum(k-1));
}
}
You have this question kind of inside out. If you want to know how many terms you need to add to get to 12, you'll have to reverse your algorithm. Keep adding successive k / (2k + 1) for larger and larger k until you hit your desired target. With your current sum method, you would have to start guessing at starting values of k and perform a sort of "binary search" for an acceptably close solution.
I don't think that this problem should be solved using recursion, but... if you need to implement it on that way, this is a possible solution:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
double result = 0;
double expectedValue = number;
int k = 0;
while (result < expectedValue) {
k++;
result = sum(k);
}
System.out.println(k
+ " is the term that should be added in order to reach "
+ number + " (" + sum(k) + ")");
}
public static double sum(double k) {
if (k == 1)
return 1 / 3;
else
return ((k / (2 * k + 1)) + sum(k - 1));
}
}

Scope Issue, I cannot calculate percentage because of this.

import java.util.Random;
import java.util.Scanner;
public class Carpim {
Scanner input = new Scanner(System.in);
Random myRandom = new Random();
public void determine(){
int trueNumber = 0;
int wrongNumber = 0;
int total = 0;
int answer = 0;
for (int i = 0; i < 5; ++i){
int num1 = 1 + myRandom.nextInt(11);
int num2 = 1 + myRandom.nextInt(11);
int correctResult = num1 * num2;
System.out.println( num1 + "*" + num2 + " What is the answer?");
answer = input.nextInt();
if (answer == correctResult){
++trueNumber;
++total;
}else if (answer != trueNumber){
++total;
++wrongNumber;
}//end if statement
}//end for loop
percentage(total, wrongNumber);
}//end method
private int percentage(int total, int wrongNumber){
int percentage = (total - wrongNumber)/total;
System.out.println(total + " " + wrongNumber + " " + percentage );
return percentage;
}//end private method.
}//End Class
Here is my code, when i run this code, this cannot calculate percentage at the end. However, it can calculate wrongNumber and total numbers. Can you please help me and tell what is wrong with this code ?
division integer with integer produces integer in java not floating point number
First, dividing integers will produce an integer result - throwing away the decimal portion of the number. You can fix that by changing your code to this:
double percentage = (double)(total - wrongNumber)/total;
...then returning the double.
Also, you're throwing away the return value of percentage(). I don't think you meant to do that, so you would want to save it in some sort of variable inside of your method, then either print or return it.
in your percentage function, you have int percentage. integer cannot contain decimal values and (total - wrongNumber) / total < 0;
Your private method should be mindful of datatypes:
private double percentage(int total, int wrongNumber){
double percentage = (double)(total - wrongNumber)/total;
System.out.println(total + " " + wrongNumber + " " + percentage );
return percentage;
}//end private method.
You should use a floating point data type to retain the decimal values in a % value.
If you want a quick way to get your percentage to 2 decimal places, you can do this:
double percentage = 56.4332893723;
percentage = ((int)(percentage*100))/100.0; // instant 2-decimal conversion

Categories