开发者

Different outputs for same algorithm in different languages

Java Source Code:

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));
    }

}

C source code:

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){
          开发者_如何学Python      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;
    }

There is no logical difference between this 2 codes for the 3n+1 problem algorithm.Only problem is in C it gives 476 as maximum cycle number where as in java it is 525...why??


In most C compilers long is generally defined as a 4-byte integer (short for long int). In Java, long is defined as an 8-byte integer.

You can change your Java code to use int for a 4-byte integer, or use long long in your c program for an 8-byte integer (I think this was added in C99, it may or may not be available on your compiler).


Java defines the size and representation of integer types, C does not. In Java, a long is a 64-bit 2's complement number. In C, it is at least 32 bits, perhaps more, and may be signed, unsigned, 1's complement, 2's complement, sign and magnitude, or other.

Did you notice that if you change this line of your Java code

long n = i;

to this

int n = (int)i;

That you get the same result as your C code? Probably you are on a 2's complement machine and your C compiler decided that longs are 32 bits.


In Java code, in method max_cycle(long j,long k), max is initialized to -1 where as in C code it is 1. Just check, if this is causing the logical error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜