Home > Software design >  How to convert "unsigned long long int" into Java?
How to convert "unsigned long long int" into Java?

Time:07-31

Here is a code written in C. It receives an integer as command line argument, and calcurate recurrence relation.

I would like to convert this code into Java, but not sure how to rewrite the following part. Does anyone know how can I write it by Java?

unsigned long long int gn[3]={0,0,1}, tmp;

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    unsigned long long int gn[3]={0,0,1}, tmp;
    int i, j;
    int n = atoi(argv[1]);
    for(i=3; i<=n; i  ){
        tmp = 0;
        for(j=0; j<3; j  ){
            tmp  = gn[j];
        }
        gn[0] = gn[1];
        gn[1] = gn[2];
        gn[2] = tmp;
    }
    if(n<2){
        printf("%ld\n",gn[n]);
    }else{
        printf("%llu\n",gn[2]);
    }
    return 0;
}

Result

Input: 1, Output: 0

Input: 5, Output: 4

Input: 10, Output: 81

Input: 30, Output: 15902591

CodePudding user response:

Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:

Long l1 = Long.parseUnsignedLong("17916881237904312345");

To print it, you can not simply print l1, but you have to first:

String l1Str = Long.toUnsignedString(l1)

Then System.out.println(l1Str);

If you are using Java version less than Java 8 then you should use BigInteger

CodePudding user response:

This looks trivial to rewrite with BigInteger. Note that argv[0] in C is the program name. Java does not follow that convention. So it might look something like,

BigInteger[] gn = { BigInteger.ZERO, BigInteger.ZERO, BigInteger.ONE };
int n = Integer.parseInt(args[0]);
for (int i = 3; i <= n; i  ) {
    BigInteger tmp = BigInteger.ZERO;
    for (int j = 0; j < 3; j  ) {
        tmp = tmp.add(gn[j]);
    }
    gn[0] = gn[1];
    gn[1] = gn[2];
    gn[2] = tmp;
}
System.out.println(gn[Math.min(n, 2)]);
  • Related