小编Ges*_*alt的帖子

尽管使用 Long 原始类型和 Big Integer 的大型斐波那契序列的整数溢出

我正在制作一个程序来打印第 n 个斐波那契数。

方法FIBBO(int n)使用 long 和 BigInteger 类型的组合来存储斐波那契运算的结果。当认为prev+next>Long.MAX_VALUE using big_flag时,该方法假设切换到使用BigInteger。然而,这个程序只有在我在第二个循环中使用 Integer.MAX_VALUE 时才有效。

当我使用 Long.MAX_VALUE 时,无论 n 的值有多大,现在都不会触发 big_flag 的第二个循环,并且我只得到垃圾值。我不明白为什么当我使用 Long.MAX_VALUE 时我的溢出逻辑永远不会被激活。

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

public class fibbo_iteration{
    public static void main(String argss[])
    {
        BigInteger result;                      
        Scanner input=new Scanner(System.in);
        int n=0;                                
        System.out.println("Enter number of terms for fibbonacci sequence");
        n=input.nextInt();
        if(n<0){
            System.out.println("Fibbonaci sequence cannot be generated for the entered negative value");
            System.exit(1);
        }
        
        result=fibbo_iteration.FIBBO(n);        //call
        System.out.println(result.toString());  
    }
    static BigInteger FIBBO(int n)
    {
        // variables
        long …
Run Code Online (Sandbox Code Playgroud)

java integer-overflow biginteger bigint long-integer

3
推荐指数
1
解决办法
79
查看次数

使用java中的递归查找数字的以2为底的对数

我正在尝试用 Java 编写一个递归方法来查找 2 的倍数的基数 2 日志。

我已经使用这种递归方法成功计算了日志。

import java.util.*;

class temp
{
    static int log(int number)
    {
        if(number==1)
            return 0;
        return log(number/2)+1;
    }   
    public static void main(String s[])
    {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter Multiple of 2:");
        System.out.println("Log is:"+log(input.nextInt())); //calling log with return value of nextInt()
    }
}   
Run Code Online (Sandbox Code Playgroud)

我搁浅的地方是尝试使用不同的方法来实现相同的程序,在这种方法中,我在递归调用中从 2 开始乘以直到它等于给定的数字。这是我尝试过的:

class logarithmrecursion
    {
        static int step=1;
        static int log(int number)
        {
            final int temp=number;
            if(number>=temp && step!=1)
                return 0;
            step++;
            return log(number*2)+1;
            
        }
    }
Run Code Online (Sandbox Code Playgroud)

在第一次调用期间,number 等于 temp,所以我使用了一个步进变量来防止终止条件的执行。如果我在递归调用中不使用“number”变量,我就没有办法累积前一个乘积但 number 变量已经等于 …

java recursion tail-recursion

0
推荐指数
1
解决办法
171
查看次数