Generating series using Java,
1*3*5 + 2*5*8 + 3*7*11......
And show the sum.
I tried this way, but didn't work. Any better algorithm to generate this series?
public static void main(String[] args) {
int sum1 = 1;
int sum2 = 0;
int sum3 = 0;
int num = 0;;
for(int i=1; i<5; i++) {
for(int j=1; j<3; j++) {
for(int k=1; k <= i+1; k++) {
num++;
}
sum1 *= num;
}
sum2 += sum1;
}
}
Since you need to generate the sum of a series of N elements, you only need a single loop (no need for nested loops).
You should notice that the elements of the series can be computed as:
Element(1) = 1 * 3 * 5
...
Element(i) = i * j * k
Element(i+1) = (i+1) + (j+2) * (k+3)
Therefore, you can use 3 variables to calculate the current element to be added to the sum.
int sum = 0;
int j = 3;
int k = 5;
for(int i = 1; i <= N; i++) {
sum += i * j * k;
j+=2;
k+=3;
}
or
int sum = 0;
for(int i = 1, j = 3, k = 5; i <= N; i++, j+=2, k+=3) {
sum += i * j * k;
}
You can try the next simple code
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int num = 0;
int series = 10;
int result = 0;
for(int i=1; i<series; i++){
sum1 = i;
sum2 = sum1+sum1+1;
sum3 = sum2+sum1+1;
System.out.print(sum1+"*"+sum2+"*"+sum3+"+");
result += sum1 * sum2 * 3;
}
System.out.print("Final result: "+result);
}
You should be able to do it in one loop like this
public static void main(String args[]){
int first = 1;
int second = 3;
int third = 5;
int n = 5;
int sum = 0;
for(int i=0;i<n;i++){
sum+=first*second*third;
first++;
second+=2;
third+=3;
}
}
for (i = 1; i <= limit; i++) {
sum += (i * (i+i+1) * (i+i+i+2))
}
I have assumed this logic :
1 : [1] * ([1] + 2) * (([1] + 2) + 2)
2 : [2] * ([2] + 3) * (([2] + 3) + 3)
3 : [3] * ([3] + 4) * (([3] + 4) + 4)
.
.
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.