首頁 >後端開發 >C++ >C程式用於計算等比數列的第N項

C程式用於計算等比數列的第N項

王林
王林轉載
2023-09-11 21:21:031136瀏覽

C程式用於計算等比數列的第N項

Given 'a' the First term, 'r' the common ratio and 'n' for the number of terms in a series. The task is to find the nth term of the series .

So, before discussing how to write a program for the problem first we should know what is Geometric Progression.

#Geometric progression or Geometric sequence in matheeachs areere Geometric term term or found by multiplying the previous one with the common ratio for a fixed number of terms.

Like 2, 4, 8, 16, 32.. is a geometric progression with first term 2 and common fratio 2. Igeometric progression with first term 2 and common fratio 2. Igeometric have n = 4 then the output will be 16.

So, we can say that Geometric Progression for nth term will be like −

GP1 = a1
GP2 = a1 * r^(2-1)
GP3 = a1 * r^(3-1)
. . .
GPn = a1 * r^(n-1)

So the formula will be GP = a * r^ (n-1).

Example

Input: A=1
   R=2
   N=5
Output: The 5th term of the series is: 16
Explanation: The terms will be
   1, 2, 4, 8, 16 so the output will be 16
Input: A=1
   R=2
   N=8
Output: The 8<sup>th</sup> Term of the series is: 128

我們將使用的方法來解決給定的問題

  • 取第一項A,公比R,以及序列的數量N。
  • 然後透過A * (int)(pow(R, N - 1) 計算第n項。
  • 傳回上述計算得到的輸出。

演算法

Start
   Step 1 -> In function int Nth_of_GP(int a, int r, int n)
      Return( a * (int)(pow(r, n - 1))
   Step 2 -> In function int main()
      Declare and set a = 1
      Declare and set r = 2
      Declare and set n = 8
      Print The output returned from calling the function Nth_of_GP(a, r, n)
Stop

Example

#include <stdio.h>
#include <math.h>
//function to return the nth term of GP
int Nth_of_GP(int a, int r, int n) {
   // the Nth term will be
   return( a * (int)(pow(r, n - 1)) );
}
//Main Block
int main() {
   // initial number
   int a = 1;
   // Common ratio
   int r = 2;
   // N th term to be find
   int n = 8;
   printf("The %dth term of the series is: %d</p><p>",n, Nth_of_GP(a, r, n) );
   return 0;
}

輸出

The 8th term of the series is: 128

以上是C程式用於計算等比數列的第N項的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除