zoukankan      html  css  js  c++  java
  • [Project Euler] 来做欧拉项目练习题吧: 题目016

                                                   [Project Euler] 来做欧拉项目练习题吧: 题目016

                                                                           周银辉 

    问题描述

    215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

    What is the sum of the digits of the number 21000? 

    问题分析:

    直接用大数乘法就可以解决,并且速度挺快(言下之意"所以没有去找其他的招了").

    将数字转换成字符串进行处理,2^m = 2^(m-1) * 2 我们将2^(m-1)放在字符数组buffer中,与2相乘时进位放在字符数组temp中,然后就可以模拟乘法了。 

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define POWER  1000
    #define BUF_SZ 310
    int test(char *buffer, char *temp)
    {
    buffer[BUF_SZ-1] = '2';
    int i, j, a, b, c;
    for(i=2; i<=POWER; i++)
    {
    for(j=BUF_SZ-1; j>=0; j--)
    {
    a = (int)buffer[j]-48;
    b = (int)temp[j]-48;
    c = a*2+b;
    buffer[j] = (char)(c%10+48);
    if(j>0)
    {
    temp[j-1] = (char)(c/10+48);
    }
    }
    }
    int result=0;
    for(i=0; i<BUF_SZ; i++)
    {
    result += (int)buffer[i]-48;
    }
    return result;
    }
    int main()
    {
    char *buffer = (char*)malloc(sizeof(char)*BUF_SZ);
    char *temp   = (char*)malloc(sizeof(char)*BUF_SZ);
    memset(buffer, '0', BUF_SZ);
    memset(temp,   '0', BUF_SZ);
    printf("sum is: %d\n", test(buffer,temp));
    printf("buffer is: %s\n", buffer);
    free(buffer);
    free(temp);
    return 0;
    }

    BUF_SZ之所以取310,因为我偷偷用计算器算了下2^1000的数量级是301,呵呵

    在我的机器上(intel 2.4G双核):

    real    0m0.011s

    user    0m0.007s

    sys     0m0.003s 

  • 相关阅读:
    vue-router 动态路由匹配
    vue-router $route
    vuex mapActions
    vuex mapMutations 使用
    ES6 动态计算属性名
    vuex Payload 荷载
    vuex mapGetters
    vuex mapState使用
    Vue 引入ElementUI 2.0.11:依赖未发现的问题
    vuex 深入理解
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/1965334.html
Copyright © 2011-2022 走看看