in code below should multiply 2 numbers. works 3 , less 3 digits numbers when give numbers 4 digits or bigger gives runtime error: stackoverflow exception unhandled
. i've commented problem is. thought problem defining variables in int
, changed them in long problem still exists. mistake?
edited: now,whats think problem?it doesnt anything
public long prod2(long u, long v) { var numbers = textbox7.text.split(',').select(p => long.parse(p)).toarray(); int n = math.max((int)math.floor(math.log10(u) + 1),(int)math.floor(math.log10(v) + 1)); int threshold = 3; if (u == 0 || v == 0) { return 0; } else if (n <= threshold) { return u * v; } else { int m = (int)math.ceiling(n / 2.0); int x = (int)(u / math.pow(10, m)); int y = (int)(u % math.pow(10, m)); int w = (int)(u / math.pow(10, m)); int z = (int)(v % math.pow(10, m)); long r = prod2(x + y, w + z); long p = prod2(x, w); long q = prod2(y, z); return p * (long)math.pow(10, 2 * m) + (r - p - q) * (long)math.pow(10, m) + q; long result = prod2(numbers[0], numbers[1]); textbox1.text = result.tostring(); } }
edit: i've translated algorithm described in book you:
public long prod2(long u, long v) { int n = math.max((int)math.floor(math.log10(u) + 1), (int)math.floor(math.log10(v) + 1)); int threshold = 3; if(u == 0 || v == 0) { return 0; } else if(n <= threshold) { return u * v; } else { int m = (int)math.ceiling(n / 2.0); int x = (int)(u / math.pow(10, m)); int y = (int)(u % math.pow(10, m)); int w = (int)(u / math.pow(10, m)); int z = (int)(v % math.pow(10, m)); long r = prod2(x + y, w + z); long p = prod2(x, w); long q = prod2(y, z); return p * (long)math.pow(10, 2 * m) + (r - p - q) * (long)math.pow(10, m) + q; } }
to right result, you'd call method other method this:
void main() { // call method , store result in variable 'r'. long r = prod2(1234, 5678); console.writeline(r); ///////////////////////////////// // // or - in case read textbox7 , store result in textbox1 // ///////////////////////////////// var numbers = textbox7.text.split(',').select(p => long.parse(p)).toarray(); long result = prod2(numbers[0], numbers[1]); textbox1.text = result.tostring(); }
so in event handler, example button1
, you'd this make call:
public void button1_click() { var numbers = textbox7.text.split(',').select(p => long.parse(p)).toarray(); long result = prod2(numbers[0], numbers[1]); textbox1.text = result.tostring(); }
don't modify prod2
have, , paste code. way, prod2 calculation , button1_click
controls input , output.
Comments
Post a Comment