Which Java data type would be able to store a big numerical value, like 9999999999?
Your concrete example could be stored in long (or java.lang.Long if this is necessary).
If at any point you need bigger numbers, you can try
java.math.BigInteger (if integer), or java.math.BigDecimal (if decimal)
In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:
long l1 = 9999999999; // this won't compile
long l2 = 9999999999L; // this will work
You can store this in a long. A long can store a value from -9223372036854775808 to 9223372036854775807.
A primitive long or its java.lang.Long wrapper can also store ten digits.
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
you can use long or double.
You could store by creating an object that hold a string value number to store in an array list.
by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");
objt is created by the constructor of BigInt class. Inside the class look like.
BigInt{
ArrayList<Integer> myNumber = new ArrayList <Integer>();
public BigInt(){}
public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }
}
A wrapper class java.lang.Long can store 10 digit easily.
Long phoneNumber = 1234567890;
It can store more than that also.
Documentation:
public final class Long extends Number implements Comparable<Long> {
/**
* A constant holding the minimum value a {#code long} can
* have, -2<sup>63</sup>.
*/
#Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* A constant holding the maximum value a {#code long} can
* have, 2<sup>63</sup>-1.
*/
#Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}
This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.
If you want to take user input then you should take that as string, then convert that into long.
//Take user input using Scanner class
Scanner sc = new Scanner(System.in);
String str = sc.next();
//Convert that to long
long num = Long.parseLong(str);
System.out.println(num); // This is not a string anymore
Related
I'm trying to convert a String(32 digits) into a long and it returns a NumberFormatException. I've tried it with Long.parseLong() and a Long object, but bone of them worked.
code:
class ConvertStringToLong{
public static void main(String in){
long out;
out=java.lang.Long.parseLong(in);
System.out.println(out);
}
}
i also tried
class ConvertStringToLong{
public static void main(String in){
long out;
out = new Long(in);
System.out.println(out);
}
}
The long datatype is a 64-bit signed integer, so its maximum value is 2^63 - 1, which is 19 digits long. To represent larger numbers than this, you will need to use a different datatype, such as BigInteger, which allows arbitrarily large numbers. The constructor new BigInteger(String val) will parse a string as a BigInteger.
Documentation here (https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html) says that:
BigInteger must support values in the range -2^Integer.MAX_VALUE
(exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values
outside of that range. The range of probable prime values is limited
and may be less than the full supported positive range of BigInteger.
The range must be at least 1 to 2^500000000.
You can favor using a BigInteger object.
I have a number of 20 digit, which datatype will support to store this number? I have tried long, double but I 'm getting out of range.
Number = 48565664968483514466
Then I have to convert this number to Base36 to generate the barcode.
BigInteger:
The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold and also provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java.lang.Math.
Declare it as
BigInteger bi1 = new BigInteger("12345678900123");
To convert your number in base 36:
BigInteger number = new BigInteger("48565664968483514466");
String numberInBase36 = number.toString(36);
System.out.println(numberInBase36);
when I'm trying to use new BigInteger(number), I'm getting literal of type int is out of range
The syntax you are looking for is
BigInteger n = new BigInteger("48565664968483514466");
with the numeric literal as a String, since the primitive integer literals cannot hold a number this large.
BigInteger i = new BigInteger("48565664968483514466");
I'm struggling to figure out what the compile/syntax error is in my code.
public class CreditCardValidation {
public static void main (String[] args){
System.out.print(prefixMatched(4388576018402626, 4388));
}
/*
Return the number of digits in d
*/
public static int getSize(long d) {
int size = 0 ;
while( d > 0 ) {
d = d / 10 ;
size = size + 1 ;
}
return size ;
}
/*
Return the first k number of digits from number. If the number of digits in number is
less than k, return the number.
*/
public static long getPrefix(long n, int k) {
int f = getSize(n)-k;
long prefix = n/((int)(Math.pow(10, f)));
return prefix;
}
/*
Return true if the digit d is a prefix for number.
*/
public static boolean prefixMatched( long number, int d ) {
if ( d == getPrefix(number, 4))
return true ;
else
return false ;
}
}
As you can see I'm trying to call prefixMatched to check whether the credit card number meets the requiremen; if digit d is a prefix for number. However, the only thing I get back from the compiler is:
"CreditCardValidation.java:6: integer number too large: 4388576018402626
System.out.print(prefixMatched(4388576018402626, 4388));
^"
I'm sorry if my question is too vauge, this is my first post.
You need to indicate to the compiler that your constant (the CC number) is a long. Put an L on the end of the constant.
It's actually a little easier to treat CC numbers as strings and use charAt(x) to calculate check digits.
The problem is that you are specifying an integer literal 4388576018402626 and that number is larger than the maximum integer, 2147483647.
You are attempting to pass it to a method that takes a long, so make it a long literal by appending L:
System.out.print(prefixMatched(4388576018402626L, 4388));
The JLS specifies this behavior in Section 3.10.1:
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
and
It is a compile-time error if a decimal literal of type int is larger than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator (§15.15.4).
add L at the end of your literal :
4388576018402626L
You should use Long instead of Integer
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The unsigned long has a minimum value of 0 and maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
You should use following to avoid exception:
System.out.print(prefixMatched(4388576018402626L, 4388));
The L indicates given value is long. You can use either l or L but I prefer to use L because it looks goods while looking code.
Source: Oracle Docs.
For this code, I would recommend using String instead of dealing with long and int. It's far easier when trying to match the first four digits, which can be isolated easily using String#substring: (String_name).substring(0,4) will be return first four digits of the String. This can then be parsed as an int using Integer#parseInt, or simply compared to another String (if the prefix were a String as well).
I am creating a bank account.which has a 'accnum' as variable.which has integer value with size of 12 bytes.
let say the bank account number is 180020131111.How do you initialize to a variable?
public class number{
public static void main(String[] args){
private long x=180020131111; // is not working..
System.out.println(x);
}
}
180020131111 is an integer literal, which cannot fit into an int type. You should append an L at the end to make it long literal.
private long x = 180020131111L;
Well, I would rather store account number as String. I don't think there is really any need for storing it as numeral, as you are just going to display it. I mean it would really look weird if you are going to do some arithmetic operations on account numbers.
By default Integral Literals are treated as 32 bit int and not 64 bit long in java..
Use this
private long x=180020131111L;
The character l ot L at the end makes integral literals long
The largest Java primitive integral type is long which is a 64 bit (8 byte) signed type. If you want to represent numbers larger that 263 - 1 == 9,223,372,036,854,775,807, you need to use BigInteger or BigDecimal.
The problem with this statement ...
private long x=180020131111;
... is that you are using the syntax for an int literal. A long literal requires a l or L suffix. (FWIW - this number does not require 9 bytes to represent ...)
Getting following run-time error
C:\jdk1.6.0_07\bin>java euler/BigConCheck
Exception in thread "main" java.lang.NumberFormatException: For input string: "z
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.math.BigInteger.<init>(BigInteger.java:314)
at java.math.BigInteger.<init>(BigInteger.java:447)
at euler.BigConCheck.conCheck(BigConCheck.java:25)
at euler.BigConCheck.main(BigConCheck.java:71)
My Code
package euler;
import java.math.BigInteger;
class BigConCheck
{
public int[] conCheck(BigInteger big)
{
int i=0,q=0,w=0,e=0,r=0,t=0,mul=1;
int a[]= new int[1000];
int b[]= new int[7];
BigInteger rem[]= new BigInteger[4];
BigInteger num[]= new BigInteger[4];
for(i=0;i<4;i++)
num[i]=big; // intialised num[1 to 4][0] with big
String s="1",g="0";
for(i=0;i<999;i++)
s = s.concat(g);
BigInteger divi[]= new BigInteger[4];
for(i=0;i<5;i++)
{
divi[i]=new BigInteger(s);
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
divi[i]=divi[i].divide(zz);
}
for(i=0;i<996;i++) // 5 consecative numbers.
{
for(int k=0;k<5;k++)
{
rem[k] = num[k].mod(divi[k]);
b[k]=rem[k].intValue();
mul= mul*b[k];
/*int z = (int)Math.pow((double)10,(double)(k+1));
String zz = "z";
BigInteger zzz = new BigInteger(zz);
num[k]=num[k].divide(zzz); */
}
a[i]=mul;
for(int p=0;p<5;p++)
{
BigInteger qq = new BigInteger("10");
num[p]=num[p].divide(qq);
}
}
return a;
}
public int bigestEleA(int u[])
{
int big=0;
for(int i=0;i<u.length;i++)
if(big<u[i])
big=u[i];
return big;
}
public static void main(String args[])
{
int con5[]= new int[1000];
int punCon;
BigInteger bigest = new BigInteger("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450");
BigConCheck bcc = new BigConCheck();
con5=bcc.conCheck(bigest);
punCon=bcc.bigestEleA(con5);
System.out.println(punCon);
}
}
please point out whats goes wrong # runtime and why
thanks in advance...
This is the line causing you grief:
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
While BigInteger does work with String's, those String's must be parsable into numbers.
EDIT**
Try this:
Integer z = (Integer)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(z.toString());
new BigInteger("z"); is not meaningful. You can only pass numbers in constructor.
This is pretty obvious, so the next time you get an exception go the the exact line in your code shown in the exception stacktrace and you will most likely spot the problem.
BigInteger Javadoc states for BigInteger(String value)
Translates the decimal String
representation of a BigInteger into a
BigInteger. The String representation
consists of an optional minus sign
followed by a sequence of one or more
decimal digits. The character-to-digit
mapping is provided by
Character.digit. The String may not
contain any extraneous characters
(whitespace, for example).
So your code:
BigInteger zz = new BigInteger("z"); // intialised div[1 to 4][0] with big
is totally incorrect, but this is correct:
BigInteger zz = new BigInteger("5566");
EDIT: Based on your comment, this would be simpler by using the String.valueOf() method:
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(String.valueOf(z));
BigInteger zz = new BigInteger("z");
you are passing non-numerical string thats the reason.
EDIT:
It takes string but it expects the string to be a numerical value. "z" does not have any numerical meaning.
Could it be that you want this instead?
int z = (int)Math.pow((double)10,(double)i);
BigInteger zz = new BigInteger(z);
Note the missing quotes here. (Of course, this will only work for i < 10.)
A common mistake is writing
new BigInteger("",num)
instead of
new BigInteger(""+num)
For those interested in generating longs with characters without hashing, it is possible to transform characters to long via BigInteger simply by using the constructor with a radix: BigInteger(String value, int radix)
There is a catch thought, the int which defines the log base, must scale not with the length of the String, but instead with the number of characters that make out the collection of characters that will be used in the creation of the String.
As far as I'm aware, for an alpha numeric collection, the int is 36 (26 + 10), this may be wrong thought.
There is also a limitation, I believe there are symbols that simply cannot be parsed, like "-" or " " or "_" (I've tried adding to the int base radix and nothing) which means the String must be transformed before parsing and it cannot be returned back to String after it being parsed via BigInteger.
Why is it useful?? I don't know haha, I have use it to autogenerate id's from Strings ,instead of using hashes, I remember somhwere this is kinda better than hashcode since a hash from String does not ensure uniqueness, an also this method as opposed to base Encoding gives extricity a long value, which may be useful for many api's that require a long id.