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