// HOMEWORK // add methods to find the area and circumference of a circle // add a method to find factorial of a long int that returns long // this is Kelvin Lam solution to the above homework public static double areaOfCirc(double rad){ return Math.PI * rad * rad; } public static double circOfCirc(double rad){ return 2 * Math.PI * rad; } public static long factorial(long n){ // precondition: n is supplied by the user // postcondition: the factorial of n is calculated iteratively and returned long f=1; for (;n>0;n--) f*=n; return f; } // recursive implementation of factori
// recursive implementation of factorial method public static long fact(long n){ // precondition: n is supplied by the user // postcondition: the factorial of n is calculated recursively and returned // base case always comes first if (n==0) return 1; else return n * fact(n-1); // from the recursive definition } // add a method to compute the nth prime number and return it // add a method to generate the first n fibonacci numbers public static int nthPrime(int n){ int k; int pCtr=1; int p=2; if (n==1) return 2; while (pCtr<n) { for ( k=2;k<=Math.sqrt(++p);k++) if (p%k == 0 ) // the number prime is not a prime if true break; // exit the inner for loop since prime is not a prime // why did we exit inner for loop? if (k>Math.sqrt(p)) // p is a prime pCtr++; } return p; } public static int fib(int n){ //precondition: user supplies n // postcondition: the first n fib numbers are // generated recursively one to a line // base case if ((n==1)||(n==2)) return 1; else return fib(n-1) + fib(n-2); } public static void fibonacci(int n){ //precondition: user supplies n // postcondition: the first n fib numbers are // generated iteratively one to a line int ctr=1; if (n==1) System. out.println("fib"+ctr+":"+ 1); else if (n==2){ System. out.println("fib"+ ctr+":"+ 1); System. out.println("fib"+ ++ctr+":"+ 1); } else{ int current=1; int prev=1; int next; System. out.println("fib"+ ctr+":"+ 1); System. out.println("fib"+ ++ctr+":"+ 1); for (;ctr<=n;ctr++) {next=prev +current; System. out.println("fib"+ ++ctr+":"+ next); prev=current; current=next; } } } }
any1 can solve this ?
Join our real-time social learning platform and learn together with your friends!