zoukankan      html  css  js  c++  java
  • 算法竞赛入门经典第二版——第二章例题

    例题2-1 aabb

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

    代码:

    #include <stdio.h>
    
    int main()
    {
        for (int x = 1;; x++)
        {
            int n = x * x;
            if (n < 1000)
            {
                continue;
            }
            if (n > 9999)
            {
                break;
            }
            int hi = n / 100;
            int lo = n % 100;
            if (hi / 10 == hi % 10 && lo / 10 == lo % 10)
            {
                printf("%d
    ", n);
            }
        }
    }
    

    例题2-2 3n+1问题

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

    输入n,输出变换的次数。n<=10^9

    样例输入:
    3
    样例输出:
    7
    

    代码:

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

    例题2-3 近似计算

    计算 $ frac π4 =1-frac 13+frac 15-frac 17+··· $,直到最后一项小于10^-6

    代码:p

    #include <stdio.h>
    
    int main()
    {
        double sum = 0, t;
        int n = 0;
        do
        {
            t = 1.0 / (2 * n + 1);
            if (n % 2)
                sum -= t;
            else
                sum += t;
            n++;
        } while (t >= 1e-6);
        printf("%.6f
    ", sum);
        return 0;
    }
    
  • 相关阅读:
    CRB and His Birthday(2015多校)
    B. Bear and Three Musketeers
    Uva657
    cas服务端改造
    有用的maven插件
    maven管理的非标准目录
    struts2中的action交由spring管理
    数据库分库
    linux内核系列之二_资源
    linux内核系列之一_工具
  • 原文地址:https://www.cnblogs.com/techoc/p/13490472.html
Copyright © 2011-2022 走看看