ในที่นี้เราได้รับจำนวนเต็ม n กำหนดจำนวนพจน์ของอนุกรม 1/1 + ( (1+2)/(1*2) ) + ( (1+2+3)/(1*2*3) ) + … + ไม่เกิน n เงื่อนไข .
งานของเราคือสร้างโปรแกรมที่จะหาผลรวมของอนุกรม 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + … ไม่เกิน n เงื่อนไข .
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
ป้อนข้อมูล
n = 3
ผลผลิต
3.5
คำอธิบาย − (1/1) + (1+2)/(1*2) + (1+2+3)/(1*2*3) =1 + 1.5 + 1 =3.5
วิธีแก้ปัญหาง่ายๆ คือการวนลูปจาก 1 ถึง n จากนั้นให้บวกค่าของผลรวมของ i หารด้วยผลคูณไม่เกิน i
อัลกอริทึม
Initialise result = 0.0, sum = 0, prod = 1 Step 1: iterate from i = 0 to n. And follow : Step 1.1: Update sum and product value i.e. sum += i and prod *= i Step 1.2: Update result by result += (sum)/(prod). Step 2: Print result.
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
double result = 0.0 ;
int sum = 0, prod = 1;
for (int i = 1 ; i <= n ; i++) {
sum += i;
prod *= i;
result += ((double)sum / prod);
}
return result;
}
int main() {
int n = 12;
cout<<"Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto "<<n<<" terms is " <<calcSeriesSum(n) ;
return 0;
} ผลลัพธ์
Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto 12 terms is 4.07742