閱讀到的一些經(jīng)典C/C++語言算法及代碼般婆。在此分享到腥。
1、計算Fibonacci數(shù)列
Fibonacci數(shù)列又稱斐波那契數(shù)列蔚袍、黃金分割數(shù)列:1左电、1、2页响、3篓足、5、8闰蚕、13栈拖、21……
C語言實現(xiàn)代碼:
代碼 1
#include <stdio.h>
int main()
{
int count, n, t1 = 0, t2 = 1, display = 0;
printf("Enter number of terms: "); //輸出項數(shù)
scanf("%d", &n);
printf("Fibonacci Series: %d + %d + ", t1, t2); //輸出第一第二項
count = 2;
//從第三項開始循環(huán)輸出斐波那契數(shù),直至輸出n個數(shù)停止。
while (count < n)
{
display = t1 + t2; //后一個數(shù)為前兩項數(shù)之和
t1 = t2;
t2 = display;
++count; //已經(jīng)輸出的項數(shù)
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); //輸出數(shù)值上限
printf("Fibonacci series: %d + %d +", t1, t2); //輸出前兩項
display = t1 + t2;
//輸出第三項及其后的斐波那契數(shù)生巡,直至輸出的數(shù)即將大于num為止
while (display < num)
{
printf("%d + ",display);
t1 = t2;
t2 = display;
display = t1 + t2; //若此數(shù)大于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、質(zhì)數(shù)檢查
只能被1和它本身整除的數(shù)本缠,1既不是質(zhì)數(shù)胰柑,也不是合數(shù)卡睦。
#include <stdio.h>
#include <math.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
//質(zhì)數(shù)檢查
if(n == 1)
printf(" 1 is not a prime number or composite number. " );
else
{
for (i = 2; i <= sqrt(n); ++i) //感謝@Angelas提醒優(yōu)化器仗。判斷次數(shù)由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;
}