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

Project Euler 80: Square root digital expansion

时间:2019-02-20 19:53:21      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:target   add   todo   res   valueof   oid   its   code   https   

题目链接

思路:

http://www.mathblog.dk/project-euler-80-digits-irrational-square-roots/

上面的链接有一个方法,用迭代法求到达某个精度的值

代码:

import java.math.*;
import java.util.*;

public class Main {
    public static BigInteger Sqrt(int n, int d) {
        BigInteger limit = BigInteger.valueOf(10).pow(d+1);
        BigInteger b = BigInteger.valueOf(5);
        BigInteger a = BigInteger.valueOf(n).multiply(b);
        while(b.compareTo(limit) < 0) {
            if(a.compareTo(b) >= 0) {
                a = a.subtract(b);
                b = b.add(BigInteger.valueOf(10));
            }
            else {
                a = a.multiply(BigInteger.valueOf(100));
                b = ((b.divide(BigInteger.valueOf(10))).multiply(BigInteger.valueOf(100))).add(BigInteger.valueOf(5));
            }
        }
        return b.divide(BigInteger.valueOf(100));
    }
    public static int Count(BigInteger n) {
        int res = 0;
        while(n.compareTo(BigInteger.valueOf(0)) > 0) {
            res += Integer.valueOf(n.remainder(BigInteger.valueOf(10)).toString());
            n = n.divide(BigInteger.valueOf(10));
        }
        return res;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int ans = 0;
        for (int i = 2; i < 100; ++i) {
            if(i == 4 || i == 9 || i == 16 || i == 25 || i == 36 || i == 49 || i == 64 || i == 81) continue;
            ans += Count(Sqrt(i, 100));
        }
        System.out.println(ans);
        
    }
}

 

Project Euler 80: Square root digital expansion

标签:target   add   todo   res   valueof   oid   its   code   https   

原文地址:https://www.cnblogs.com/widsom/p/10408632.html

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