algorithm - Karatsuba multiplication java recursion code not working? -
i trying multiply 2 numbers using karatsuba multiplication. java code not working. have used string parameters , arguments can multiply 2 n digit numbers (n even). also, don't want use long or biginteger. please me figure out code mistake.
class karat{ public static string karatsuba(string first, string second){ if(first.length() <= 1 || second.length() <= 1) return string.valueof(long.parselong(first)*long.parselong(second)); string = karatsuba(first.substring(0, first.length()/2), second.substring(0, second.length()/2)); string b = karatsuba(first.substring(first.length() - first.length()/2, first.length()), second.substring(second.length() - second.length()/2, second.length())); string c = karatsuba(string.valueof(long.parselong(first.substring(0, first.length()/2)) + long.parselong(first.substring(first.length() - first.length()/2, first.length()))), string.valueof(long.parselong(second.substring(0, second.length()/2)) + long.parselong(second.substring(second.length() - second.length()/2, second.length())))); string d = string.valueof(long.parselong(c) - long.parselong(b) - long.parselong(a)); return string.valueof(((int)math.pow(10, first.length()))*(long.parselong(a)) + (((int)math.pow(10, first.length()/2))*long.parselong(d)) + (long.parselong(c))); } public static void main(string[] args){ string result = karatsuba("1234", "5678"); system.out.println(result); } }
can please refine code.
numbers passed multiplication - 1234 , 5678
output - 6655870 (incorrect)
output should - 7006652 (correct)
thank
interesting algorithm. 1 mistake in
return string.valueof(((int)math.pow(10, first.length()))*(long.parselong(a)) + (((int)math.pow(10, first.length()/2))*long.parselong(d)) + (long.parselong(c)));
at end, should long.parselong(b)
instead of long.parselong(c)
.
and in intermediate calculations, can happen 2 strings of different lengths. doesn't work correctly.
please, allow comments improve implementation. idea use strings seems allow big numbers, introduce things long.parselong()
or (int)math.pow(10, first.length())
, limiting long
or int
range.
if want big numbers, write own string-based addition , power-of-ten multiplication (that 1 being trivial appending zeroes).
and, try avoid names a, b, c, or d - it's easy forget mean, original mistake. e.g. names wikipedia little bit better (using z0, z1 , z2), still not perfect...
Comments
Post a Comment