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