2

I am trying to implementing Karatsuba's algorithm from wikipedia and I cannot continue to code since I do not know to how to split an integer into lower-half and upper-half. For example, if we have an integer 223, then it should be split into two integer 22 and 3.

How I might do this?

so it has to be something like

num1 = 223;

some magical stuff happening here!

low1 = 22;
low2 = 3;

Thank you very much I really appreciate your help!

4
  • 1
    have you learnt about the modulo(%) operation? if you haven't, go and check that out. :) Commented Nov 7, 2013 at 1:51
  • Yep, modulo arithmetic is your friend. Commented Nov 7, 2013 at 1:52
  • You could easily do this, if you did sum of digits of a given integer :) Commented Nov 7, 2013 at 1:53
  • just realised.! I am having a headache now! thanks! mod! Commented Nov 7, 2013 at 1:55

4 Answers 4

5
low1 = num1 / 10;
low2 = num1 % 10;

This is the gist of what you're trying to accomplish. I'm not familiar with the algorithm and what exactly you're trying to do, so extra logic will almost certainly be required, but this is a good starting point.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1917231, Vote? No you can't right now that requires at least 15 reputation. You can right now accept the answer instead.
3

You can use the modulus (%) operator to extract digits from a number. For example

12345 % 10   = 5
12345 % 100  = 45
12345 % 1000 = 345

And so on. Hope this helps.

Comments

0

you can use the modulus (%) operator to remove out the last number of an integer

int num1 = 223;
int num2 = num1%10;

num2 = 3 in this case

1 Comment

The first line of your answer is misleading and should be reworded. For example, %2 doesn't return the last number (it can only return 0 or 1). And the phrase "remove out"? The original number remains unmodified.
0

I would suggest this algorithm to split an integer :

int i = 233678546; /* The integer you would like to split */

int digitNumber = String.valueOf(i).length(); /* use java.math.Math.log10 if you need a more mathematical approach */

double val = Math.pow(10.0, (double)(digitNumber / 2)); 
int div = new Double(val).intValue();

int left = i / div;
int right = i % div;

StringBuilder sb = new StringBuilder();
sb.append("Value : ");
sb.append(i);
sb.append('\n');

sb.append("Left : ");
sb.append(left);
sb.append('\n');

sb.append("Right : ");
sb.append(right);
sb.append('\n');

System.out.println(sb.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.