草庐IT

java - 查找数字 (4+sqrt(11))^n 的小数点前的最后两位数字

coder 2024-03-08 原文

我正在做一道题,我必须找到数字
[4 + sqrt(11)]n.

例如,当 n = 4, [4 + sqrt(11)]4 = 2865.78190... 时,答案是 65。其中 n 可以从 2 变化<= n=""><=>9

我的解决方案 - 我尝试构建一个平方根函数来计算 11 的平方根 精度等于用户输入的n值。

我用过BigDecimal在 Java 中避免溢出问题。

public class MathGenius {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        long a = 0;
        try {
            a = reader.nextInt();
        } catch (Exception e) {
            System.out.println("Please enter a integer value");
            System.exit(0);
        }

        // Setting precision for square root 0f 11. str contain string like 0.00001
        StringBuffer str = new StringBuffer("0.");
        for (long i = 1; i <= a; i++)
            str.append('0');
        str.append('1');

        // Calculating square root of 11 having precision equal to number enter
        // by the user.
        BigDecimal num = new BigDecimal("11"), precision = new BigDecimal(
                str.toString()), guess = num.divide(new BigDecimal("2")), change = num
                .divide(new BigDecimal("4"));
        BigDecimal TWO = new BigDecimal("2.0");
        BigDecimal MinusOne = new BigDecimal("-1"), temp = guess
                .multiply(guess);
        while ((((temp).subtract(num)).compareTo(precision) > 0)
                || num.subtract(temp).compareTo(precision) > 0) {

            guess = guess.add(((temp).compareTo(num) > 0) ? change
                    .multiply(MinusOne) : change);

            change = change.divide(TWO);
            temp = guess.multiply(guess);
        }

        // Calculating the (4+sqrt(11))^n
        BigDecimal deci = BigDecimal.ONE;
        BigDecimal num1 = guess.add(new BigDecimal("4.0"));
        for (int i = 1; i <= a; i++)
             deci = deci.multiply(num1);

        // Calculating two digits before the decimal point
        StringBuffer str1 = new StringBuffer(deci.toPlainString());
        int index = 0;
        while (str1.charAt(index) != '.')
            index++;
        // Printing output

        System.out.print(str1.charAt(index - 2));
        System.out.println(str1.charAt(index - 1));
    }
}

此解决方案适用于 n = 200,但随后开始变慢。它在 n = 1000 时停止工作。

什么是处理问题的好方法?

2 -- 53
3 -- 91
4    65
5    67
6    13
7    71
8    05
9    87
10   73
11   51
12   45
13   07
14   33
15   31
16   85
17   27
18   93
19   11
20   25
21   47
22   53
23   91
24   65
25   67

最佳答案

在 n=22 时,结果似乎从 n=2 的位置开始重复。 因此,将这 20 个值按照与列表中相同的顺序保存在数组中,例如nums[20]

然后当用户提供一个 n 时:

return nums[(n-2)%20]

现在有这种模式重复的证明 here .

或者,如果你坚持计算长度;因为您是通过循环乘法(而不是 BigDecimal pow(n))来计算幂的,所以您可以将前面使用的数字修剪到最后 2 位数字和小数部分。

关于java - 查找数字 (4+sqrt(11))^n 的小数点前的最后两位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21964541/

有关java - 查找数字 (4+sqrt(11))^n 的小数点前的最后两位数字的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  4. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  5. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  6. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  7. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  8. 区块链之加解密算法&数字证书 - 2

    目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非

  9. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  10. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

随机推荐