Intro
This time, I have attempted to prove the following bruteforce multiplication formula: $$ (a_n \cdots a_0) \cdot (b_m \cdots b_0) = \sum_{i = 0}^n \sum_{j = 0}^m a_i b_j \cdot 10^{i + j}, $$ where \$a_n, \ldots, a_0, b_m, \ldots, b_0 \in \{ 0, 1, \ldots, 9\}\$ are decimal digits.
Code
com.github.coderodde.research.multiply.BruteForceMultiply.java:
package com.github.coderodde.research.multiply;
import java.util.Scanner;
/**
* This class provides the method for doing brute-force integer multiplication.
*/
public final class BruteForceMultiply {
/**
* This method performs the brute-force integer operation for non-negative
* long integers.
*
* @param number1 the first number.
* @param number2 the second number.
* @return the product of {@code number1} and {@code number2}.
*/
public static long multiply(final long number1, final long number2) {
checkNotNegative(number1);
checkNotNegative(number2);
final String number1String = Long.toString(number1);
final String number2String = Long.toString(number2);
final long[] a = convertLongStringToDecimalDigitArray(number1String);
final long[] b = convertLongStringToDecimalDigitArray(number2String);
long product = 0L;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
product += a[i] * b[j] * myPow(10, i + j);
}
}
return product;
}
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(">>> ");
final long a = scanner.nextLong();
final long b = scanner.nextLong();
System.out.println(multiply(a, b));
}
}
private static void checkNotNegative(final long number) {
if (number < 0) {
final String exceptionMessage =
String.format("number(%d) < 0", number);
throw new IllegalArgumentException(exceptionMessage);
}
}
private static long[] convertLongStringToDecimalDigitArray(
final String numberString) {
final long[] digitArray = new long[numberString.length()];
for (int i = 0; i < digitArray.length; i++) {
digitArray[i] = numberString.charAt(digitArray.length - 1 - i)
- '0';
}
return digitArray;
}
private static long myPow(final long base, final long exponent) {
long p = 1L;
for (int i = 0; i < exponent; i++) {
p *= base;
}
return p;
}
}
com.github.coderodde.research.multiply.BruteForceMultiplyTest.java:
package com.github.coderodde.research.multiply;
import org.junit.Test;
import static org.junit.Assert.*;
public final class BruteForceMultiplyTest {
@Test
public void bruteforceTest() {
for (long a = 0L; a < 1000L; a++) {
for (long b = 0L; b < 1000L; b++) {
assertEquals(a * b,
BruteForceMultiply.multiply(a, b));
}
}
}
}
Critique request
Please, as always, give me any critique regarding any aspect of my code.
myPow()... Doesint==longin Java??? \$\endgroup\$