例题2-1 aabb
输出所有形如aabb的四位完全平方数(即前两位数字相等,后两位数字也相等)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int i, j, n;
double m;
for(i = 1; i <= 9; i++)
for(j = 0; j <= 9; j++)
{
n = i*1100 + j*11;
//n = (i*10+i)*100 + j*10 + j;
m = sqrt(n);
if(floor(m+0.5) == m) printf("%d\n", n);
}
system("PAUSE");
return 0;
}
int main(int argc, char *argv[])
{
int x, y;
for(x = 33; x*x <= 9999; x++)
{
y = x*x;
if(y/1000 == y/100%10 && y/10%10 == y%10)
printf("%d\n", y);
}
system("PAUSE");
return 0;
}
总结:1 一组逆向的思维解决同一个问题
2 用变量n = a*1100 + b*11来储存四位数
3 浮点运算会存在误差。在进行浮点数误差时,应考虑到浮点误差 如 floor(m+0.5) == m
例题2-2 3n+1问题 猜想:对于任意大于1的自然数n,若n为奇数,则将n变成3n+1,否则变成一半 经过若干次这样的变换,一定会使n变成1.例如3->10->5->16->8->4->2->1 输入n,输出变换的次数。n≤10^9. 样例输入:3 样例输出:7
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
unsigned n, count = 0;
scanf("%d", &n);
while(n > 1)
{
if(n % 2 == 1) { n = n + (n+1)/2; count += 2; continue;}
else n >>= 1 ;
count++;
}
printf("%d\n", count);
system("PAUSE");
return 0;
}总结:1 3n+1会溢出4 (3n+1)/2不如写做 n + (n+1)/2,减少溢出的可能
例题2-3 阶乘之和
输入n,计算S=1!+2!+3!+……+n!的末6位(不含前导0),n≤10^6
#include <cstdlib>
#include <stdio.h>
int main()
{
const int MOD = 1000000;
int n;
long long sum = 0, tem = 1;
scanf("%d",&n);
for (int i=1; i<=n; i++)
{
tem = tem*i%MOD ;
sum = (sum+tem)%MOD;
}
printf("%d\n",sum);
system("PAUSE");
return EXIT_SUCCESS;
}
原文地址:http://blog.csdn.net/oceaniwater/article/details/40587713