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 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; { 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; }
there no logical difference between 2 codes 3n+1 problem algorithm.only problem in c gives 476 maximum cycle number in java 525...why??
java defines size , representation of integer types, c not. in java, long
64-bit 2's complement number. in c, @ least 32 bits, perhaps more, , may signed, unsigned, 1's complement, 2's complement, sign , magnitude, or other.
did notice if change line of java code
long n = i;
to this
int n = (int)i;
that same result c code? on 2's complement machine , c compiler decided long
s 32 bits.
Comments
Post a Comment