The series: 1×2 2×3×4 ... n×(n 1)× ... ×2n
For example, if you enter 3, the output should be 386, because (1×2) (2×3×4) (3×4×5×6)=386.
I've tried various loops, but that is not even close to the desired result.
Though, I'll post it here:
int sum = 0, n = sc.nextInt();
for (int i = 1; i <= n; i ) {
sum = sum i * (i 1);
}
CodePudding user response:
I do not intent to resolve it for you, but you are missing that multiplication itself needs another loop for each of the number in the loop you created (from n to 2n).
I am giving you the solution, but hope you will try to understand it to realize where you missed it.
public class MyClass {
private static long calculateSeries(int n){
long sum=0;
for (int i = 1; i <= n; i ) {
// You are missing multiplication part in your logic.
long mres=1;
for (int j=i; j <= 2*i; j ){
mres=mres*j;
}
sum = sum mres;
}
return sum;
}
public static void main(String args[]) {
System.out.println(calculateSeries(3));
}
}
CodePudding user response:
I will do one better and give you advice on how to approach problems. Divide it into smaller problems :)
I wont give you the end result code, I think you wont learn much from it, but I will try to help you solve it learn from it.
So in words - given number N, sum the results of the multiplication of all the numbers between i to 2i for each 1<= i <= N.
So what you want to do:
- receive input N
- loop on all the numbers between 1 to N - you did everything until here, awesome :)
- sum the results of the multiplication of all the numbers between i to 2i - this logic is incorrect in your code, I advise you to create a function that do this multiplication, just call and sum it in the loop from step #2