码迷,mamicode.com
首页 > 其他好文 > 详细

立方尾不变

时间:2018-07-22 15:16:58      阅读:735      评论:0      收藏:0      [点我收藏+]

标签:除了   stdio.h   alt   code   block   src   amp   分享图片   bubuko   

题目描述:

找出数字的立方末尾正好是该数字的数字。
如:1, 4, 5, 6, 9, 24, 25
范围:10000

解题思路:

  1. 要取出一个整数的后n位,用整数 % 10^n。
    如:1024,取出后两位,1024 % 10^2 = 24。
  2. 数字最大为10000^3,一般的类型肯定装不下。除了可以用long long外,还可以用一个小技巧:每次只保留最大数的后4位, 因为这里只需要用到末尾的几位数字,这样数字就不会超过10000,int也可轻松装下。
  3. 求一个数字的位数方法:每次数字 / 10,直到为0,用一个变量记录几次便是数字的位数。



实现代码:

#include <stdio.h>

//计算n^t
int mypow(int n, int t)
{
    int ret = 1;
    if (t >= 4 && n == 10)
    {
        while (t--)
        {
            ret *= n;
        }
        return ret;
    }

    while (t--)
    {
        ret = ret * n % 10000;
    }

    return ret;
}

//获取数字的位数
int get_len(int n)
{
    int len = 1;
    int tmp = n / 10;
    while (tmp != 0)
    {
        len++;
        tmp /= 10;
    }

    return len;
}

int main()
{
    int i, tmp, count = 0;
    int cunum;  //立方值
    
    for (i = 1; i <= 10000; i++)
    {
        cunum = mypow(i, 3);  //i^3
        if (cunum == 0)
            continue;
        tmp = get_len(i);
        tmp = cunum % mypow(10, tmp);
        if (i == tmp)
        {
            printf("%d\n", i);
            count++;
        }
    }
    printf("%d", count);

    return 0;
}

Output:

技术分享图片

立方尾不变

标签:除了   stdio.h   alt   code   block   src   amp   分享图片   bubuko   

原文地址:https://www.cnblogs.com/coolcpp/p/cube-tail.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!