Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert "unsigned long long int" into Java?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

>Solution :

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)]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading