An Odd Way To Square (Java)

Question is from here.

Write a function that takes a positive integer n and returns n-squared. You may use addition and subtraction but not multiplication or exponentiation.

Your task is to write the squaring function described above.

Solution:

public class An_Odd_Way_To_Square {
	public static void main(String[] args) {
		square(2);
		square(4);
		square(10);
	}

	private static void square(int n) {
		if(n < 0)
			throw new NumberFormatException("Negative number!");
		int count = n, res = 0;

		while(count > 0) {
			res += n;
			count--;
		}
		System.out.println(res);
	}
}

Output:

4
16
100
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s