Как найти сумму арифметического ряда на нескольких языках

Арифметическая последовательность – это последовательность, в которой каждый член отличается от предыдущего на постоянную величину. И знание того, как их найти, может помочь вам сформировать свой набор навыков программирования, какой бы язык (языки) вы не использовали.

В этой статье вы узнаете, как найти сумму арифметических рядов с помощью Python, C ++, JavaScript и C.

Что такое арифметический ряд?

Сумма членов конечной арифметической последовательности называется арифметическим рядом. Арифметическая последовательность обозначается следующим образом:

 a, a+d, a+2d, a+3d, a+4d, ...

куда,

 a = First term
d = Common difference

Постановка задачи

Вам дан первый член, общая разница и нет. членов арифметического ряда. Вам нужно найти сумму арифметического ряда. Пример : Пусть firstTerm = 1, commonDifference = 2 и noOfTerms = 5. Арифметический ряд: 1 + 3 + 5 + 7 + 9 Сумма арифметического ряда: 25 Таким образом, на выходе будет 25.

Итерационный подход к нахождению суммы арифметического ряда

Сначала мы рассмотрим итеративный подход. Вы можете узнать, как таким способом найти суммы для основных языков программирования, ниже.

Программа на C ++ для нахождения суммы арифметического ряда с помощью итераций

Ниже приведена программа на C ++ для нахождения суммы арифметического ряда с помощью итерации:

 // C++ program to find the sum of arithmetic series
#include <iostream>
using namespace std;
// Function to find the sum of arithmetic series
int sumOfArithmeticSeries(int firstTerm, int commonDifference, int noOfTerms)
{
int result = 0;
for (int i=0; i<noOfTerms; i++)
{
result = result + firstTerm;
firstTerm = firstTerm + commonDifference;
}
return result;
}
int main()
{
int firstTerm = 1;
int commonDifference = 2;
int noOfTerms = 5;
cout << "First Term: " << firstTerm << endl;
cout << "Common Difference: " << commonDifference << endl;
cout << "Number of Terms: " << noOfTerms << endl;
cout << "Sum of the arithmetic series: " << sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms) << endl;
return 0;
}

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Программа Python для нахождения суммы арифметического ряда с помощью итераций

Ниже приведена программа Python для нахождения суммы арифметического ряда с использованием итерации:

 # Python program to find the sum of arithmetic series
# Function to find the sum of arithmetic series
def sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms):
result = 0
for i in range(noOfTerms):
result = result + firstTerm
firstTerm = firstTerm + commonDifference
return result
firstTerm = 1
commonDifference = 2
noOfTerms = 5
print("First Term:", firstTerm)
print("Common Difference:", commonDifference)
print("Number of Terms:", noOfTerms)
print("Sum of the arithmetic series:", sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms))

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Связанный: Как использовать циклы For в Python

Программа на JavaScript для поиска суммы арифметического ряда с помощью итераций

Ниже приведена программа на JavaScript для нахождения суммы арифметического ряда с помощью итерации:

 // JavaScript program to find the sum of arithmetic series
// Function to find the sum of arithmetic series
function sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms) {
var result = 0;
for (let i=0; i<noOfTerms; i++)
{
result = result + firstTerm;
firstTerm = firstTerm + commonDifference;
}
return result;
}

var firstTerm = 1;
var commonDifference = 2;
var noOfTerms = 5;
document.write("First Term: " + firstTerm + "<br>");
document.write("Common Difference: " + commonDifference + "<br>");
document.write("Number of Terms: " + noOfTerms + "<br>");
document.write("Sum of the arithmetic series: " + sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms));

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Связанный: Как найти произведение всех элементов в массиве

Программа на C для поиска суммы арифметического ряда с помощью итераций

Ниже приведена программа на языке C для нахождения суммы арифметического ряда с помощью итерации:

 // C program to find the sum of arithmetic series
#include <stdio.h>
// Function to find the sum of arithmetic series
int sumOfArithmeticSeries(int firstTerm, int commonDifference, int noOfTerms)
{
int result = 0;
for (int i=0; i<noOfTerms; i++)
{
result = result + firstTerm;
firstTerm = firstTerm + commonDifference;
}
return result;
}
int main()
{
int firstTerm = 1;
int commonDifference = 2;
int noOfTerms = 5;
printf("First Term: %d ⁠n", firstTerm);
printf("Common Difference: %d ⁠n", commonDifference);
printf("Number of Terms: %d ⁠n", noOfTerms);
printf("Sum of the arithmetic series: %d ⁠n", sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms));
return 0;
}

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Эффективный подход к нахождению суммы арифметического ряда с помощью формулы

Вы можете использовать следующую формулу, чтобы найти сумму арифметического ряда:

 Sum of arithmetic series = ((n / 2) * (2 * a + (n - 1) * d))

куда,

 a = First term
d = Common difference
n = No. of terms

Программа на C ++ для нахождения суммы арифметического ряда с помощью формулы

Ниже приведена программа на C ++ для нахождения суммы арифметического ряда по формуле:

 // C++ program to find the sum of arithmetic series
#include <iostream>
using namespace std;
// Function to find the sum of arithmetic series
int sumOfArithmeticSeries(int firstTerm, int commonDifference, int noOfTerms)
{
return (noOfTerms / 2) * (2 * firstTerm + (noOfTerms - 1) * commonDifference);
}
int main()
{
int firstTerm = 1;
int commonDifference = 2;
int noOfTerms = 5;
cout << "First Term: " << firstTerm << endl;
cout << "Common Difference: " << commonDifference << endl;
cout << "Number of Terms: " << noOfTerms << endl;
cout << "Sum of the arithmetic series: " << sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms) << endl;
return 0;
}

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Программа Python для нахождения суммы арифметического ряда с помощью формулы

Ниже приведена программа Python для нахождения суммы арифметического ряда по формуле:

 # Python program to find the sum of arithmetic series
# Function to find the sum of arithmetic series
def sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms):
return (noOfTerms / 2) * (2 * firstTerm + (noOfTerms - 1) * commonDifference)
firstTerm = 1
commonDifference = 2
noOfTerms = 5
print("First Term:", firstTerm)
print("Common Difference:", commonDifference)
print("Number of Terms:", noOfTerms)
print("Sum of the arithmetic series:", sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms))

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Связанный: Как реализовать линейный поиск с использованием рекурсии в C, C ++, Python и JavaScript

Программа на JavaScript для нахождения суммы арифметического ряда с помощью формулы

Ниже приведена программа на JavaScript для нахождения суммы арифметического ряда по формуле:

 // JavaScript program to find the sum of arithmetic series
// Function to find the sum of arithmetic series
function sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms) {
return (noOfTerms / 2) * (2 * firstTerm + (noOfTerms - 1) * commonDifference);
}

var firstTerm = 1;
var commonDifference = 2;
var noOfTerms = 5;
document.write("First Term: " + firstTerm + "<br>");
document.write("Common Difference: " + commonDifference + "<br>");
document.write("Number of Terms: " + noOfTerms + "<br>");
document.write("Sum of the arithmetic series: " + sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms));

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Программа на C для нахождения суммы арифметического ряда с помощью формулы

Ниже приведена программа на языке C, позволяющая найти сумму арифметического ряда по формуле:

 // C program to find the sum of arithmetic series
#include <stdio.h>
// Function to find the sum of arithmetic series
int sumOfArithmeticSeries(int firstTerm, int commonDifference, int noOfTerms)
{
return (noOfTerms / 2) * (2 * firstTerm + (noOfTerms - 1) * commonDifference);
}
int main()
{
int firstTerm = 1;
int commonDifference = 2;
int noOfTerms = 5;
printf("First Term: %d ⁠n", firstTerm);
printf("Common Difference: %d ⁠n", commonDifference);
printf("Number of Terms: %d ⁠n", noOfTerms);
printf("Sum of the arithmetic series: %d ⁠n", sumOfArithmeticSeries(firstTerm, commonDifference, noOfTerms));
return 0;
}

Выход:

 First Term: 1
Common Difference: 2
Number of Terms: 5
Sum of the arithmetic series: 25

Найти арифметические серии с разными языками программирования легко

Теперь, когда вы прочитали эту статью, вы знаете, как найти арифметические серии с каждым из основных языков программирования.

C ++ – один из языков программирования "хлеб с маслом". Он используется для разработки разнообразного программного обеспечения, такого как базы данных, операционные системы, компиляторы, веб-браузеры и т. Д. Если вы хотите изучить C ++, вам следует посетить некоторые из лучших сайтов, такие как Udemy, edX, LearnCpp и т. Д.