Handling large numbers - java

I have this problem:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
My code converts the input to a string and evaluates either end of the string making adjustments accordingly and moves inwards. However, the problem requires that it can take values up to 10^6 digits long, if I try to parse large numbers I get a number format exception i.e.
Integer.parseInt(LARGENUMBER);
or
Long.parseInt(LARGENUMBER);
and LARGENUMBER is out of range. can anyone think of a work around or how to handle such large numbers?

You could probably use the BigInteger class to handle large integers like this.
However, I wouldn't count on it being efficient at such massive sizes. Because it still uses O(n^2) algorithms for multiplication and conversions.

Think of your steps that you do now. Do you see something that seems a little superfluous since you're converting the number to a string to process it?

While this problem talks about integers, its doing so only to restrict the input and output characters and format. This is really a string operations question with careful selection. Since this is the case, you really don't need to actually read the input in as integers, only strings.
This will make validating the palindrome simple. The only thing you should need to work out is choosing the next higher one.

Related

Creating a BigInteger from String and pad "0"s to it

[InputParam1:Decimal Number in String format(for Eg:30),
InputParam2:Integer to denote number of repeating 0's to append(for Eg:6)]
For converting a number from Decimal to Binary and pad digits to its front I need to perform the following steps:
Step1: BigInteger binary=new BigInteger(InputParam1,2);
-->This works when I define a BigInt with a base 16 (which I just tried when base2 failed) but not with a base 2 like above.
It throws a numberformat exception.
Step 2: String pad=StringUtils.repeat("0",InputParam2);
(to repeat 0 'InputParam2' number of times)
-->This works fine
Step 3: Need to append pad in front of binary(from Step1)
For a BigInteger, I'm not able to get something similar to .append.
So I'm trying to a)convert this BigInteger number to String and b)append pad c)convert back to BigInteger (this step I'm not able to get without creating a new BigInteger)
Any pointers on Step1 and Step3-c would be helpful please.
#1 - You haven't said what value you're passing in InputParam1, but my guess is that you're passing in something other than a string containing only '0' in '1' characters. The 'radix' parameter to the constructor tells the code how to interpret the string you're giving it. This works fine for me:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
How you construct the number has nothing to do with how you're eventually going to want to represent or display that number. The key idea here is that the representation of a number (hex, decimal, binary) has nothing to do with the number itself, just like leading zeros don't affect the value of number. 1111 binary, f hex, and 15 decimal are all the same number. If you pass the three of these into BigDecimal's constructor with a radix of 2, 16 and 10 respectively, you'll end up with EXACTLY the same thing in each case. The object will lose any notion of what kind of representation you used to set it to its initial value.
#3 - There is no concept of a number (int, BigInteger, etc.) with zero padding at the front, just as there's no notion of which base/radix you might use to represent a number visually. You can think about it conceptually, but that's just a way of displaying the number. It has nothing to do with the number itself.
I hadn't tried it before, but it seems there's no super simple way to format a binary value in Java with leading 0s, like there is for decimal and hex, since String.format() doesn't give a format specifier for binary. Per this StackOverflow post How to get 0-padded binary representation of an integer in java?, this seems to be about the best way to go, having converted the most accepted answer to work with BigInteger:
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
So here's all of my sample code, with output:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
System.out.println(str);
Output:
8
0000000000001000

How can I find if a given integer value of n digits contains a particular digit in less than linear time?

I could only think of ways in which you would need to check each digit of the input value at least once to search for the digit.
As I understand, converting into string and using inbuilt functions like ".contains()" takes even longer.
Is there some algorithm or optimization that I can use to know if a particular digit is contained in the integer value in less than linear time with reference to number of digits in the value?
The input value may have as many as a hundred thousand digits.
Update: I have to work on 15 separate queries, each having one large integer of less than 10^6 digits(generated randomly), I have to determine if this value contains a particular digit(and keep a count upto 2 occurances,anything more can be ignored).
I wish to know if there is a way to perform this act of "digit-searching" in the integer value in less than linear time.

Count how long the floating point is

How can I count how long the floating point is?
e.g.
count(10.123); //result: 3
count(10); //result: 0
count(10.3771) //result: 4
I know how to count it when transforming to a string, but that isn't very efficient, is it?
A double is always a specific length. It will only show the numbers need to obtain the accuracy.
ie. 10.3771 is the equivilant to 00000010.37710000 (not the exact number of 0's that are really there, I'm just trying to explain the concept).
In reality even this is inaccurate as a double is a 64 bit binary number
Converting it to String is your best bet and not an inefficient method.

Can someone explain the Math.ulp(double) method?

I haven't been able to find any information online that doesn't already assume I know things. I wonder if anyone knows any good resources that I can look into to help me wrap my head around what this function does exactly?
From what I gather, and I'm pretty certain this is wrong or at least not fully right, is that given a floating point, it determines the distance between itself and some number next in a sequence? There appears to be something to do with how number are represented bitwise, but the sources I've read never explicitly said anything about that.
http://matlabgeeks.com/tips-tutorials/floating-point-comparisons-in-matlab/
illustrated it rather well:
float2bin(A)
//ans = 0011111110111001100110011001100110011001100110011001100110100000
float2bin(B)
//ans = 0011111110111001100110011001100110011001100110011001100110011010
You can see the difference in precision at a binary level in this example. A and B differ by 6 ulps (units in the last place)
I believe that it is showing the distance between the number you specify, and the next largest binary float that can be encoded.
Because of the range that binary floating point numbers cover and their precision, not all numbers between any two given real numbers are covered, so it looks like this is giving you the positive distance between the number you wish to encode and the actual number it would be stored as.
From Wikipedia:
the unit of least precision (ULP) is the spacing between floating-point numbers, i.e., the value the least significant digit represents if it is 1

How to do arithmetic operations in binary with Java?

For a Java assignment I am required to be able to pass any number that will be introduced as a string through the command line (no matter how big) into binary.
Then generate methods that will allow these numbers to add, multiply, subtract and divide.
My question would be first:
How do I make my string into binary
Eg:
123 would become 1111011
8403678 would become 100000000011101011011110
And so forth...
Then the biggest issue is to get them to add up, subtract each other, etc.
Last I need to be able to convert back the result from binary back to decimal which I am having more trouble understanding how to do it than the previous case (transforming from binary into a decimal string).
Eg:
if 1111011 was added to 100000000011101011011110 the result would be 100000000011101101011001 and then it would become 8403801 which I would print out as a result.
The final aim of this project is to create our own class such as java.math.BigInteger (without using it of course) and handling arbitrarily big numbers (bigger than what Int can handle).
If there is any extra information required please let me know I will answer promptly.
Since you have to be able to handle large numbers without using BigInteger, you need to find a way to represent arbitrarily large numbers. Obviously int will not do. One easy way is to represent the number as a String. For instance, the number 123 could be stored as the String "123".
Converting to binary will require some intermediate operations such as division and modulo. Thus, it is worth thinking about how to do these when your numbers are stored in Strings. Since this is homework I don't want to just give you the answer, but some guidance instead.
Say you want to do addition.
Think about how you add big numbers by hand. Which digits of each number do you use, and how do you manipulate them to get the answer? This algorithm is fairly straightforward, and once you can explain it, you can give a computer directions to do it as well. (For addition, you add first the one's digits, then the ten's digits, etc... and remember to carry if you have to!)
Note that you can get the digits of your number String by using a method such as charAt(int n). This will return the character at index n of the string. Convert it to an Integer by using Integer.parseInt() (which takes a numeric string and converts it to an integer).
So now you can think: If I want the one's digit of a number, what index would that be in a String? Starting with this, you should be able to figure out how to get any digit you want from a big number string. Now, you can implement your algorithm.
Finally, to convert from base ten to binary you do need to understand how number bases work. This gives a clear and quick introduction: http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary
The section "Converting from decimal to binary" in the above link describes a method for exactly what you want to do. Good luck.

Categories

Resources