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));
}
}
Related
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.
Consider the sequence X1=1, X2= 1+1/1, X3= 1+1/1+1/1... . In this sequence Xn+1 = 1+1/Xn (for n>= 1). Write a method in Java that computes Xn. As n increases, the terms of this sequence get closer and closer to the golden ratio 1+sqrt 5/ 2 ~ 1.61803398875. How close is X10 to the golden ratio?
This is the program that I have written but when I run it in java it does not compile. I do not know what to do and it is due tomorrow. Please help!
public class Golden Ratio
{
public static final double GOLDEN = ( 1 + Math.sqrt(5))/2;
/**
* precondition: Class(Golden Ratio), n values
* precondition: sequence values found
*/
public static double sequence (int n)
{
if (n == 0) {
return 1;
{
public static void main(String[] args)
{
for (int n = 0; n < 40; n++)
{
double diff = Math.abs(sequence(n) - GOLDEN);
System.out.print(n+1+")");
System.out.print(n + 1 < 10 ? " seq " + sequence(n): "seq " + sequence (n))
System.out.print("gld " + GOLDEN);
System.out.print("diff = %.32f\t". diff);
System.out.print("\n");
}
System.out.print("\n");
System.out.print("10)" + "sqe " + sequence(9) + "ln gld + GOLDEN"\t diff = %.32 f\t" + diff);
System.out.print("");
}
}
}
Your function should do all the calculating work. Your main method just calls it and presents the results. Here is how it's structured. You'll still need to do the part that calculates the sequence. Double-check the definition, before you do the work, though. If X3=1 + 1/1 + 1/1, then that's the same as saying X3=3, which is obviously wrong.
public static double calculateSequence(int n) {
double sum=0.0;
for (int i=0; i<n; i++) {
// do your magic
}
return sum;
}
public static void main(String[] args) {
double answer=calculateSequence(10);
System.out.println("%f is off by %f", answer, GOLDEN_RATIO - answer);
}
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
import java.util.Scanner;
public class PowersOf2
{
public static void main(String[] args)
{
int inputPowersOf2;
int PowerOf2 = 1;
int exponent;
int exponent2;
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
inputPowersOf2 = scan.nextInt();
System.out.println("\n\n");
if(inputPowersOf2 >= 2)
{
System.out.println("Here are the first " + inputPowersOf2 + " powers of 2:");
System.out.println();
}
else
{
System.out.println("Here is the first power of 2:");
System.out.println();
}
exponent2 = 0;
exponent = 0;
while(exponent <= inputPowersOf2)
{
System.out.print("2^" + exponent2 + " = ");
exponent2++;
System.out.println((PowerOf2 = 2 * PowerOf2) / 2);
exponent++;
}
}
}
why is it when i say give me 1 power of two it prints
2^0
2^1
and when i say give me 2 powers of two it prints
2^0
2^1
2^2
and so on...
Replace
while(exponent <= inputPowersOf2)
with
while(exponent < inputPowersOf2)
As others said in comments, this is very, very easy to solve using the debugger.
Hope that helps,
You could retrace the steps manually on a paper using small inputs and then proceed to larger inputs.
just replace the code while(exponent <= inputPowersOf2) because it runs one extra time becuase of the "=" sign.