欧拉工程第40题: Champernowne's constant

题目链接: https://projecteuler.net/problem=40
按照自然数链接起来的数字,求出其中几个位置数的乘积。

这个很简单,就在注意在判断时候别出小错
1-N 遍历,求一个数的长度,再求累加长度,判断累加长度是否是所求的位置

Java代码:

package projecteuler31to40;

import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

class level40{  
    void solve(){
        //d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
        int Max_Value=1000000;
        int result=1;
        int number=0;
        int d=1;
        for(int i=1;i<Max_Value;i++){
            int before=String.valueOf(i).length();
            if(number<d && number+before<=d && d<=1000000){
                if(number+before==d){
                    d=d*10;
                    result*=Integer.parseInt(String.valueOf(i).substring(before-1));
                }
                number+=before;
            }else if(number<d && number+before>d && d<=1000000){
                result*=Integer.parseInt(String.valueOf(i).substring((d-number-1),d-number));
                number+=before;
                d=d*10; 
            }
            if(d>1000000){
                System.out.println(result);
                return ;
            }
        }

    }


}
public class Problem40 {


    public static void main(String[] args){
        Date beginTime=new Date();
        new level40().solve();
        Date endTime=new Date();
        long Time=endTime.getTime()-beginTime.getTime();
        System.out.println("Time:"+Time/1000+"s"+Time%1000+"ms");
    }

}

结果:

210
Time:0s54ms

Python代码:

def calcPos(pos):
    digitString = ''
    n = 1
    while n <= pos:
        digitString += str(n)
        n += 1
    return int(digitString[pos-1])

from time import time
t0=time()
print calcPos(1) * calcPos(10) * calcPos(100) * calcPos(1000) * \
      calcPos(10000) * calcPos(100000) * calcPos(1000000)
t1=time()
print("time is {0}".format(t1 - t0))

结果:

210
time is 5.01099991798

这个代码好无节操的暴力求解了,每次都求一次遍历有重复的,可以把连接后的结果存在长度是 1000000+1的字符串里面,每次再取出来就好了。

更新代码:

def join_digits(num):
    digitString='0'
    for i in range(1,num+1):
        digitString+=str(i)
    return digitString

from time import time
t0=time()
digitStr=join_digits(250000)
print int(digitStr[1])*int(digitStr[10])*int(digitStr[100])*\
      int(digitStr[1000])*int(digitStr[10000])*int(digitStr[100000])*int(digitStr[1000000])

t1=time()
print("time is {0}".format(t1 - t0))

结果:

210
>>> 
>>> t1=time()
>>> print("time is {0}".format(t1 - t0))
time is 1.28799986839

你可能感兴趣的:(java,python,欧拉工程)