不同语言中相同算法的不同输出

MiN*_*EaK 2 c java algorithm

Java源代码:

package n1_problem;

/**
 *
 * @author nAwS
 */
public class loop {

    int loop(long i)
    {
        long n=i;
        int count=1;
        while(n>1){
            if(n%2==0){
                n=n/2;
            }
            else{
                n=3*n+1;
            }
            count++;
        }
       return count; 
    }

    int max_cycle(long j,long k){

        int max=-1;
        for(long i=j;i<=k;i++){
            int count=loop(i);
            if(count>max){
                max=count;
            }
        }
        return max;
    }


}


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        loop lp=new loop();
        System.out.println("Max Cycle:"+lp.max_cycle(1,1000000));
    }

}
Run Code Online (Sandbox Code Playgroud)

C源代码:

int main()
{
    long r,h;
    int f=0;
    do 
    {
        printf("Value,r:");
        scanf("%ld",&r);
        printf("Value,h:");
        scanf("%ld",&h);

        f=max_cycle(r,h);
        printf("Max:%d\n",f);

    }while(getch()!='e');
}

int loop(long i)
{
        long n=i;
        int count=1;
        while(n>1)
        {
            if(n%2==0){
                n=n/2;
            }
            else{
                n=3*n+1;
            }
            count++;
        }
       return count; 
    }

    int max_cycle(long j,long k)
    {

        int max=1;
        long i=0;
        for(i=j;i<=k;i++){

            int count=loop(i);
            if(count>max){
                max=count;
            }
        }
        return max;
    }
Run Code Online (Sandbox Code Playgroud)

对于3n + 1问题算法,这2个代码之间没有逻辑上的区别.只有在C中它给出476作为最大循环数,而在java中它是525 ...为什么?

hel*_*922 5

在大多数C编译器long中,通常定义为4字节整数(简称long int).在Java中,long定义为8字节整数.

您可以更改Java代码以int用于4字节整数,或者long long在您的c程序中使用8字节整数(我认为这是在C99中添加的,它可能在您的编译器上也可能不可用).

  • +1.在Java中,它不是"通常",而是"始终". (3认同)