阅读到的一些经典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;
}
网友评论