Question

In: Computer Science

Recursion practice Write a Java program with functions for each of the following problems. Each problem...

Recursion practice

Write a Java program with functions for each of the following problems. Each problem should be solved by writing a recursive function. Your final program should not have any loops in it.

All of your solutions should be in a single .java file. The main function of the file should demonstrate each of your solutions, by running several tests and producing the corresponding outputs.

Write a recursive method to

1. calculate power of a give number

2. multiply m by n using only repeated addition

  1. Implement recursive Fibonacci: Return the nth number in the Fibonacci sequence (5 points) a. Demonstrate by printing the first 10 numbers
  2. Implement Euclid’s algorithm recursively.

a. Euclid’s algorithm to calculate the greatest common divisor of two positive integer         

numbers a and b (gcd(a,b)) is recursively defined as:

gcd(a,b) := a if a = b

gcd(a,b) := gcd(a - b, b) if a > b

gcd(a,b) := gcd(a, b - a) if b > a

  1. Return the length of a linked list
    1. You will need to implement a simple link list
    2. Include a length function that uses recursion to count the number of elements

Solutions

Expert Solution

import java.util.*;
public class Main
{
public static int calculatePower(int x,int y) //to calculate power(x,y)
{
if(y==0)
return 1;
else
return x*calculatePower(x,y-1);
}
public static int multiply(int m,int n)
{
       if(n>0)
           return m+multiply(m,n-1);//recursivly calling multiply()
       else
           return 0; //n<=0
}
public static int gcd(int a,int b) //to calculate gcd
{
if(a==b)
return a;
else if(a>b)
return gcd(a-b,b);
else
return gcd(a,b-a);
}
public static int fib(int n) //to get fibnocci series
{
if(n>1)
return fib(n-1)+fib(n-2);
else
return n; //n<=1
}
   public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       int n=sc.nextInt();
       int b=sc.nextInt();
       System.out.println(n+" power of "+b);
       System.out.println(calculatePower(n,b)); //calculatint Power
       System.out.println("multiplication of "+n+"x"+b);
       System.out.println(multiply(n,b)); //multiplication
       System.out.println("Greatest common divisor of "+n+" and "+b);
       System.out.println(gcd(n,b)); //to get gcd value
       System.out.println(n+"th Number in the fibnocci sequence is "+fib(n)); //get nth fibnocci number
       System.out.println("first 10 numbers in the fibnocci series are: ");
       System.out.println(fib(1)+"\n"+fib(2)+"\n"+fib(3)+"\n"+fib(4)+"\n"+fib(5)+"\n"+fib(6)+" \n"+fib(7)+" \n"+fib(8)+" \n"+fib(9)+"\n"+fib(10)); //printing first 10 numbers in fibnocci series without using loop (or) we can write another function for this.
       System.out.println("Single Linked List:");
       LinkedList L = new LinkedList();
L =L.insert(L, 10); //inserting elements to the list
L =L.insert(L, 20);
L =L.insert(L, 30);
L =L.insert(L, 40);
L =L.insert(L, 50);
L.printList(L); //print the list
       System.out.println();
System.out.println("Length of linked list is:");
System.out.println(L.count(L.head)); //length of list
      
   }
}
class LinkedList {
  
Node head; //starting node of list
static class Node { //static class to easy access
int data;
Node next;
Node(int d) // Constructor
{
data = d; // data to be stored in the node
next = null; //to create link betwwen nodes
}
}
public static LinkedList insert(LinkedList l, int data) // insert a new node
{
Node new_node = new Node(data);
new_node.next = null;
if (l.head == null) {
l.head = new_node;
}
else {
Node last = l.head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
return l;
}
public static int count(Node temp) //to count the number of elements in the list
{
if(temp==null)
return 0;
else
return 1+count(temp.next);
}
public static void printList(LinkedList list) //to print the list elements
{
Node n = list.head;
System.out.print("LinkedList: ");
while (n != null) {
System.out.print(n.data + " ");
n = n.next;
}
}
}

output:


Related Solutions

please use java swing and recursion and the suggested method hints listed Objective: Write a program...
please use java swing and recursion and the suggested method hints listed Objective: Write a program in which draws (yes it actually makes a picture) a triangular fractal using recursion. This is best if done using a java applet. Suggested Methodology The idea for it is this First draw a filled equilateral triangle Next draw another filled equilateral triangle of a different color that’s upside down in the middle of that triangle Using the other triangles formed repeat step 2...
Java please! Write the code in Exercise.java to meet the following problem statement: Write a program...
Java please! Write the code in Exercise.java to meet the following problem statement: Write a program that will print the number of words, characters, and letters read as input. It is guaranteed that each input will consist of at least one line, and the program should stop reading input when either the end of the file is reached or a blank line of input is provided. Words are assumed to be any non-empty blocks of text separated by spaces, and...
Write a program in python that implements quicksort, first using recursion and then without recursion.
Write a program in python that implements quicksort, first using recursion and then without recursion.
What java program would you write to solve the following problems and why does it work?...
What java program would you write to solve the following problems and why does it work? Please also comment on other students’ code at least three times. 1) Implement MyArrayStack (constructor, push, pop, peek and isEmpty), and MyLinkedQueue with both next and previous pointers (constructor, enqueuer/offer, dequeuer/poll, peek and isEmpty), and write the following two program to test them. You must use MyArrayList or MyLinkedList for the implementation. 2) For stack testing, write a program to check if a string...
Write a program in java processing. Write a program that does the following: · Assume the...
Write a program in java processing. Write a program that does the following: · Assume the canvas size of 500X500. · The program asks the user to enter a 3 digit number. · The program then checks the value of the first and last digit of the number. · If the first and last digits are even, it makes the background green and displays the three digit number at the mouse pointer. · If the two digits are odd, it...
Java Complete Example.java to fulfill the following problem statement: Write a program to accept a list...
Java Complete Example.java to fulfill the following problem statement: Write a program to accept a list of numbers, one per line. Input is provided from a file if one is provided as the first command line argument. If a file is not provided, input should be read from the terminal. The numbers can either be whole numbers or floating point numbers. The program should continue to accept input until a number equal to 00 is input. Of course, if the...
write a Java program Write a program to assign a letter grade according to the following...
write a Java program Write a program to assign a letter grade according to the following scheme: A: total score >= 90 B: 80 <= total score < 90 C: 70 <= total score < 80 D: 60 <= total score < 70 F: total score < 60 Output - the student's total score (float, 2 decimals) and letter grade Testing - test your program with the following input data: test1 = 95; test2 = 80; final = 90; assignments...
Write a complete program in java that will do the following:
Write a complete program in java that will do the following:Sports:             Baseball, Basketball, Football, Hockey, Volleyball, WaterpoloPlayers:           9, 5, 11, 6, 6, 7Store the data in appropriate arraysProvide an output of sports and player numbers. See below:Baseball          9 players.Basketball       5 players.Football           11 players.Hockey            6 players.Volleyball        6 players.Waterpolo       7 players.Use Scanner to provide the number of friends you have for a team sport.Provide an output of suggested sports for your group of friends. If your...
write C++ program using functions (separate function for each bottom) Write a program to find if...
write C++ program using functions (separate function for each bottom) Write a program to find if a number is large word for two given bottom base - bottom1 and bottom2. You can predict that a number, when converted to any given base shall not exceed 10 digits. . the program should ask from user to enter a number that it should ask to enter the base ranging from 2 to 16 after that it should check if the number is...
Write a complete Java program, including comments in each method and in the main program, to...
Write a complete Java program, including comments in each method and in the main program, to do the following: Outline: The main program will read in a group of three integer values which represent a student's SAT scores. The main program will call a method to determine if these three scores are all valid--valid means in the range from 200 to 800, including both end points, and is a multiple of 10 (ends in a 0). If the scores are...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT