SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:1 | ISBN:9780136091813 | Edition: 2

Question

Write a method called showTwos that shows the factors of 2 in a given integer. For example, consider the following calls:
showTwos(7);
showTwos(18);
showTwos(68);
showTwos(120);

These calls should produce the following output:
7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

public class FactorsOf {

	// this is a wrapper funtion to print one line only once
	public void showTwos(int value) {

		System.out.print(value + " = ");
		showTwos1(value);
	}

	// actual recursive funtion
	public void showTwos1(int value) {

		if (value < 2) {
			System.out.println(value);
			return;

		} else if (value % 2 == 1) {
			System.out.println(value);
			return;
		} else if (value % 2 == 0 && value >= 2) {
			System.out.print("2 * ");
			showTwos1(value / 2);
		}

	}

	public static void main(String[] args) {
		
		// creating object and calling funtion
		FactorsOf factors = new FactorsOf();
		factors.showTwos(7);
		factors.showTwos(18);
		factors.showTwos(68);
		factors.showTwos(120);
		
	}

}
Output:

7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15

 

0 0

Discussions

Post the discussion to improve the above solution.