Swift程式:求解小於等於N的偶數斐波那契數列之和
本教程將討論如何編寫一個Swift程式來求解小於等於數字N的偶數斐波那契數列之和。
一個數列,其中每個數都是其前兩個數之和,被稱為斐波那契數列。斐波那契數列的起始數字是0和1,所以數列為:
0, 1, 1, 2, 3, 5, 8, 13, 21, ……
能被2整除的數被稱為偶數。換句話說,完全能被2整除的數被稱為偶數。例如,2, 4, 6, 8等等。
所以我們要找到小於等於N的偶數斐波那契數列之和。
下面是一個演示:
輸入
假設我們的輸入為:
Enter the number - 10
輸出
期望的輸出為:
Sum of even Fibonacci terms are 10
這裡的輸出是10,因為在0到10的斐波那契數列中,偶數是2和8,所以2+8=10。
演算法
以下是演算法:
步驟1 - 建立一個函式。
步驟2 - 宣告四個變數,分別命名為“temp”、“sum”、“n1”、“n2”。其中sum用於儲存偶數之和,n1和n2是斐波那契數列的初始兩個值。
步驟3 - 執行一個while迴圈,直到n2 < num。
步驟4 - 使用if語句檢查偶數並計算它們的和。
if (n2 % 2 == 0) {
sum += n2
}
步驟5 - 將前兩個數字相加以找到數列中的第i個數字。
步驟6 - 返回偶數之和。
步驟7 - 呼叫該函式並傳入引數,列印輸出。
示例1
下面的程式演示瞭如何求解小於等於N的偶數斐波那契數列之和。
import Foundation import Glibc // Function to find the sum of even fibonacci terms func SumOfEvenFibonacci(num: Int) -> Int{ var temp = 0 // Store the sum of even numbers var sum = 0 // Initial two values of fibonacci sequence var n1 = 0 var n2 = 1 while(n2 < num){ // Checking for even numbers // By calculating their remainder if the remainder is 0 // then the number is number is even if not // then the number is not even if (n2 % 2 == 0){ sum += n2 } // Adding two previous numbers to find ith // number of the series temp = n1 n1 = n2 n2 += temp } return sum } print("Sum of even fibonacci terms:", SumOfEvenFibonacci(num: 100))
輸出
Sum of even fibonacci terms: 44
在上面的程式碼中,我們建立了一個名為SumOfEvenFibonacci()的函式來求解偶數斐波那契數列之和。在這個函式中,我們透過將前兩個數字相加來找到斐波那契數列,然後檢查從0到100的所有斐波那契數中的偶數,並使用以下程式碼計算偶數之和。
while(n2 < num){ if (n2 % 2 == 0){ sum += n2 } temp = n1 n1 = n2 n2 += temp } return sum
上述程式碼的工作原理是:
temp = 0 sum = 0 n1 = 0 n2 = 1 num = 100 while(1 < 100){ if (1 % 2 == 0) => (1 == 0) = condition false{ sum += n2 } temp = 0 n1 = 1 n2 = 1 + 0 = 1 } while(1 < 100){ if (1 % 2 == 0) => (1 == 0) = condition false{ sum += n2 } temp = 1 n1 = 1 n2 = 1 + 1 = 2 } while(2 < 100){ if (2 % 2 == 0) => (0 == 0) = condition true{ sum = sum + n2 => sum = 0 + 2 = 2 } temp = 1 n1 = 2 n2 = 2 + 1 = 3 } ... so on till num = 100.
現在我們呼叫該函式,並傳入100作為引數,顯示結果為44(2+8+34 = 44)。
示例2
下面的程式演示瞭如何求解小於等於N的偶數斐波那契數列之和。
import Foundation import Glibc // Function to find the sum of even fibonacci terms func SumOfEvenFibonacci(num: Int) -> Int{ var temp = 0 var sum = 0 var n1 = 0 var n2 = 1 while(n2 < num){ // Checking for even numbers if (n2 % 2 == 0){ sum += n2 } // Adding two previous numbers to find ith // number of the series temp = n1 n1 = n2 n2 += temp } return sum } // Taking input from the user print("Please enter the value:") var val = Int(readLine()!)! // Calling function var res = SumOfEvenFibonacci(num: val) print("Sum of even fibonacci terms are:", res)
標準輸入
Please enter the value: 10000
輸出
Sum of even fibonacci terms are: 3382
在上面的程式碼中,我們建立了一個名為SumOfEvenFibonacci()的函式來求解偶數斐波那契數列之和。這裡我們從使用者那裡獲取輸入,並將此輸入作為引數傳遞給SumOfEvenFibonacci()函式。假設使用者輸入數字10000,則0到10000之間所有偶數的總和為3382。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP