閱讀到的一些經典C/C++語言算法及代碼。在此分享。
1、計算Fibonacci數列
Fibonacci數列又稱斐波那契數列、黃金分割數列:1、1、2、3、5、8、13、21……
C語言實現代碼:
代碼 1
#include <stdio.h>
int main()
{
int count, n, t1 = 0, t2 = 1, display = 0;
printf("Enter number of terms: "); //輸出項數
scanf("%d", &n);
printf("Fibonacci Series: %d + %d + ", t1, t2); //輸出第一第二項
count = 2;
//從第三項開始循環輸出斐波那契數,直至輸出n個數停止。
while (count < n)
{
display = t1 + t2; //後一個數爲前兩項數之和
t1 = t2;
t2 = display;
++count; //已經輸出的項數
printf("%d + ", display);
}
return 0;
}
代碼 2
#include <stdio.h>
int main()
{
int t1 = 0, t2 = 1, display = 0, num;
printf("Enter an iteger: ");
scanf("%d", &num); //輸出數值上限
printf("Fibonacci series: %d + %d +", t1, t2); //輸出前兩項
display = t1 + t2;
//輸出第三項及其後的斐波那契數,直至輸出的數即將大於num爲止
while (display < num)
{
printf("%d + ",display);
t1 = t2;
t2 = display;
display = t1 + t2; //若此數大於num,則停止輸出
}
return 0;
}
2、迴文檢查
源代碼:
#include <stdio.h>
int main()
{
int n, reverse = 0, rem, temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp = n;
while (temp != 0)
{
rem = temp % 10;
reverse = reverse * 10 +rem;
temp /= 10;
}
if (reverse == n)
printf("%d is a palindrome", n);
else
printf("%d is not a palindrome.", n);
return 0;
}
3、質數檢查
只能被1和它本身整除的數,1既不是質數,也不是合數。
#include <stdio.h>
#include <math.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
//質數檢查
if(n == 1)
printf(" 1 is not a prime number or composite number. " );
else
{
for (i = 2; i <= sqrt(n); ++i) //感謝@Angelas提醒優化。判斷次數由n/2-1縮減到sqrt(n)-1次
{
if (n % i == 0)
{
flag = 1;
}
}
if (flag ==0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}