【算法】《算法竞赛入门经典》第二章 示例及答案

  • Post author:
  • Post category:其他



实例

程序2-1

输出1,2,3……n的值

#include<stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        printf("%d\n",i);
    return 0;
}

程序2-2

aabb

输出所有形如aabb的4位完全平方数(即前两位数字相等,后两位数字也相等)。

<pre name="code" class="cpp">/*
*7744问题--版本一
*开平方看平方根是否为整数
*/
#include<stdio.h>
#include<math.h>
int main()
{
    int a,b;
    for(int i=1; i<=9; ++i)
        for(int j=0; j<=9; ++j)
        {
            a=i*1100+j*11;
            b=floor(sqrt(a)+0.5);
            if(b*b==a)
                printf("%d\n",a);
        }
    return 0;
}


程序2-3

/*
*7744问题--版本二
*枚举平方根
*/
#include<stdio.h>
int main()
{
    int n,hi,lo;
    for(int i=1;; ++i)
    {
        n=i*i;
        if(n<1000)
            continue;
        if(n>9999)
            break;
        hi=n/100;
        lo=n%100;
        if(hi/10==hi%10&&lo/10==lo%10)
            printf("%d\n",n);
    }
    return 0;
}

程序2-4

3n+1问题

猜想:对于任意大于1的自然数n,若n为奇数,则将变为3n+1,否则变为n的一半。经过若干次这样的变换,一定会使n变为1.例如,3→ 10→ 5→ 16→ 8→ 4→2→ 1.

输入n,输出变换的次数。n≤10

9


样例输入:


3


样例输出:


7


/*
*有BUG版本
*/
#include<stdio.h>
int main()
{
    int n,count;
    scanf("%d",&n);
    count=0;
    while(n!=1)
    {
        if(n%2==1)
            n=3*n+1;
        else
            n/=2;
        ++count;
    }
    printf("%d\n",count);
    return 0;
}

程序2-5

/*
*题中一个陷阱就是当输入为987654321时,3n+1的值会溢出
*解决办法是用一个long long类型的变量存储n
*/
#include<stdio.h>
int main()
{
    int n,count;
    scanf("%d",&n);
    long long n1=n;
    count=0;
    while(n1!=1)
    {
        if(n1%2==1)
            n1=3*n1+1;
        else
            n1/=2;
        ++count;
    }
    printf("%d\n",count);
    return 0;
}

程序2-6

近似计算

计算π/4=1-1/3+1/5-1/7+……,知道最后一项小于

10


-6



版权声明:本文为White_Idiot原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。