0
Program to print series 1+1/2+1/3+1/4+1/5 by taking user input
example if input =3 then print sum of 1+1/2+1/3
4 Respuestas
+ 2
For the sake of completeness, a iterative and a recursive solution:
import java.util.Scanner;
public class Program {
private static double r(int f){
if(f == 1){
return 1d;
}else{
return 1d/f + r(f-1);
}
}
private static double i(int f){
double sum = 0;
for(int i = 1; i <= f; i++){
sum += 1d/i;
}
return sum;
}
public static void main(String[] a){
Scanner in = new Scanner(System.in);
int dep = in.nextInt();
System.out.println(i(dep));
System.out.println(r(dep));
}
}
Hm this might be nice for the challenges, think i'll submit it:)
+ 1
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter n");
int n=sc.nextInt();
double sum=0;
for(int i=1;i<=n;i++)
{
sum=sum+(double)1/i;
}
System.out.println("sum= "+sum);
}
}
+ 1
int input = 15; // or read from Scanner
double sum = 0;
for(int i = 1; i <= input; i++){
sum += 1d/i;
}
System.out.println(sum);
- 2
while(sum<input){
sum+=1;
print(sum);// or sum + "+ 1"
}