How to stop summation of a harmonic series when it reaches a given target in Java?
I am a complete newbie to Java who only recently became familiar with loops. I am trying to write a program that reads into a target and finds the first n such that 1 + 1/2 + 1/3 + ... + 1 / n> target. The problem provided code with initialization n and missing sum, and missing while condition and its statements.
I can figure out how to make a harmonic series loop, but I'm not sure what to set n to stop the loop when it exceeds the target. We have not yet learned about arrays in a class.
import java.util.Scanner;
/**
This program computes how many steps the sum 1 + 1/2 + 1/3 + ...
needs to exceed a given target.
*/
public class ReciprocalSum
{
public static void main(String[] args)
{
double sum = 0;
int n = ???? ;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
int i = 0;
//Notes
// 1 + 1/2 + 1/3 + 1/4 + ..... 1/n
//Make a loop that repeats itself starting with n = 1 --> 1/1 + 1/2 + 1/3 + 1/4 + 1/n
// 1.0/n + (1.0/ n - 1) + (1.0/n-2) +.... if n =4 --> 1/4 + 1/3 + 1/2 + 1/1 as long as n >0
while ( n > 0)
{
sum += 1.0/n ;
n--;
}
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}
source to share
Since Java 8+ has lambdas, you can generate the range 1
to n
and do your calculation and get the sum in one step. Basically, you could do
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble(), sum = 1.0;
int n = 1;
while (sum < target) {
sum = IntStream.range(1, n).mapToDouble(i -> 1.0 / i).sum();
n++;
}
System.out.printf("n=%d, sum=%.2f%n", n, sum);
source to share
You can achieve this this way by calculating the sum
series until its sum is greater than the target value:
double sum = 0;
int n = 1;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
while(sum <= target){
sum = sum + 1.0/n;
n = n + 1;
}
System.out.println(sum);
source to share