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){
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??
Java defines the size and representation of integer types, C does not. In Java, a
longis 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
to this
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.