"Integer number too large" error message for 600851475143 - java

public class Three {
public static void main(String[] args) {
Three obj = new Three();
obj.function(600851475143);
}
private Long function(long i) {
Stack<Long> stack = new Stack<Long>();
for (long j = 2; j <= i; j++) {
if (i % j == 0) {
stack.push(j);
}
}
return stack.pop();
}
}
When the code above is run, it produces an error on the line obj.function(600851475143);. Why?

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L

Append suffix L: 23423429L.
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.

You need to use a long literal:
obj.function(600851475143l); // note the "l" at the end
But I would expect that function to run out of memory (or time) ...

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.
To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.
Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).
This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

Apart from all the other answers, what you can do is :
long l = Long.parseLong("600851475143");
for example :
obj.function(Long.parseLong("600851475143"));

Or, you can declare input number as long, and then let it do the code tango :D ...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
long n = in.nextLong();
for (long i = 2; i <= n; i++) {
while (n % i == 0) {
System.out.print(", " + i);
n /= i;
}
}
}

Related

max value of iterator in for loop in java

Is long allowed inside of for loop in java? If yes, why does eclipse shows an error while putting a long value, If no, what is the maximum value that can be used inside a for loop as iterator?
Yes it is allowed. This works just fine
for(long l=0;l<Long.MAX_VALUE;l++){
System.out.println(l);
}
It is allowed, look:
for (long lng = 1L; lng < Long.MAX_VALUE; lng++) {
// your code
}
To see max long value that you can assign, you can use:
System.out.println(Long.MAX_VALUE);
Notice that I put L after literal 1 (it's 1L) when assigning value to long, to avoid error when trying to assign value exceeding Integer range (this error would occur when if you tried to assign value greater than Integer.MAX_VALUE to variable of type long without using long literal (this literal is upper- or lowercase 'L' character after digits, without 'L' it's integer literal and compiler checks that this number is currently out of int range).
When for 1 in my example this L was redundant, for numbers greater than Integer.MAX_VALUE it's necessary.
Without any code I can only guess, but I assume you're trying to use a value that's too big to fit into an int literal where you want a long.
For example:
for(long x = 0; x < 9876543210; x++) {
...
}
This code will produce The literal 9876543210 of type int is out of range because although you defined x to be of type long, the literal you're using here is interpreted as int and is therefore too big.
To fix this, you need to explicitly tell the compiler, that you mean a long literal by appending a l or L to the value (upper-case L is preferred, because you can better tell it apart from a 1):
for(long x = 0; x < 9876543210L; x++) {
... ^- notice the 'L'
}

Possible lossy conversion from long to int, can't find error [duplicate]

This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
In this code I keep getting:
error: incompatible types: possible lossy conversion from long to int
rem = num%16;
1 error
This is the code im working with currently.
public class BaseConverter{
public static String convertToBinary(long num){
long binary[] = new long[40];
int index = 0;
while(num > 0){
binary[index++] = num%2;
num = num/2;
}
for(int i = index-1; i>= 0;i--){
System.out.print(binary[i]);
}
}
public static String convertToHexadecimal(long num){
int rem;
// For storing result
String str="";
// Digits in hexadecimal number system
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(num>0)
{
rem = num%16;
str = hex[rem]+str;
num = num/16;
}
}
}
Basically, this code is supposed to help me setup for another program which calls the static methods. But I can't compile because of this error.
Your problem is on the line rem = num%16; where you are assigning a value of type long to a variable of type int.
The general rule is that the result of applying one of the arithmetic operators is the larger of the two types that are being operated on. In the words of the Java Language Specification, section 15.17
,
The type of a multiplicative expression is the promoted type of its operands.
Therefore, the expression num%16 has type long, because num has type long; even though its value will always be between -15 and 15. It's an error to assign a long expression to an int variable, without explicitly casting it.
You could write
rem = (int) num % 16;
to avoid this error.
Yes because of this code
rem = num%16;
rem is int type and num is long, you need to add type conversion
rem = (int)num%16;
Also add return statements for both of your methods for successful compilation.
use this:
rem = (int) (num % 16);
and don't forget your return statement:
return str;

possible loss of precision-with mod- (but it's not)

So this the line with the precision error fault;
A[i]= m % 3;
m is long
A is int[];
And my error is
error: possible loss of precision
A[i]= m % 3.
required int
found long.
How can I have error when the only potential answers are 0,1,2?
Isn't there another way than declaring A as long[]?
It's a potentially big array so I don't want that (in fact I would even prefer for A to be short[])
Also I tried error: A[i]= m % 3L , but same result.
The compiler doesn't look at the result, it looks at the type. The type of m%3 is long, and you are trying to put it into an int.
So, the compiler is angry, because potentially, the value stored in a longis bigger than the one you can store into an int.
In order to remove the problem, you have to cast the result back into an int:
A[i] = (int) (m % 3);
However, you can do this because you know the result is 0,1 or 2. If you do not know the value of the long you are casting, you may have an integer overflow:
public static void main(String[] args) {
long l = Integer.MAX_VALUE + 1L;
System.out.println(l);
// 2147483648
System.out.println((int)l);
// -2147483648
}

How to get the value of Integer.MAX_VALUE in Java without using the Integer class

I have this question that has completely stumped me.
I have to create a variable that equals Integer.MAX_VALUE... (in Java)
// The answer must contain balanced parentesis
public class Exercise{
public static void main(String [] arg){
[???]
assert (Integer.MAX_VALUE==i);
}
}
The challenge is that the source code cannot contain the words "Integer", "Float", "Double" or any digits (0 - 9).
Here's a succinct method:
int ONE = "x".length();
int i = -ONE >>> ONE; //unsigned shift
This works because the max integer value in binary is all ones, except the top (sign) bit, which is zero. But -1 in twos compliment binary is all ones, so by bit shifting -1 one bit to the right, you get the max value.
11111111111111111111111111111111 // -1 in twos compliment
01111111111111111111111111111111 // max int (2147483647)
As others have said.
int i = Integer.MAX_VALUE;
is what you want.
Integer.MAX_VALUE, is a "static constant" inside of the "wrapper class" Integer that is simply the max value. Many classes have static constants in them that are helpful.
Here's a solution:
int ONE = "X".length();
int max = ONE;
while (max < max + ONE) {
max = max + ONE;
}
or lots of variants.
(The trick you were missing is how to "create" an integer value without using a numeric literal or a number wrapper class. Once you have created ONE, the rest is simple ...)
A bit late, but here goes:
int two = "xx".length();
int thirtyone = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".length();
System.out.println(Math.pow(two, thirtyone)-1);
How did I go? :p
I do like that bitshift one though...
The issue is that the answer cannot contain: "Integer", "Float", "Double", and digits (0 - 9)
There are other things in Java which can be represented as an Integer, for example a char:
char aCharacter = 'a';
int asInt = (int) aCharacter;
System.out.println(asInt); //Output: 97
You can also add chars together in this manner:
char aCharacter = 'a';
char anotherCharacter = 'b';
int sumOfCharacters = aCharacter + anotherCharacter;
System.out.println(sumOfCharacters); //Output: 195
With this information, you should be able to work out how to get to 2147483647on your own.
OK, so an Integer can only take certain values. This is from MIN_VALUE to MAX_VALUE where the minimum value is negative.
If you increase an integer past this upper bound the value will wrap around and become the lowest value possible. e.g. MAX_VALUE+1 = MIN_VALUE.
Equally, if you decrease an integer past the lower bound it will wrap around and become the largest possible value. e.g. MIN_VALUE-1 = MAX_VALUE.
Therefore a simple program that instantiates an int, decrements it until it wraps around and returns that value should give you the same value as Integer.MAX_VALUE
public static void main(String [] arg) {
int i = -1
while (i<0) {
i--;
}
System.out.println(i);
}

Value change when converting a long to a double and back

given the following code:
long l = 1234567890123;
double d = (double) l;
is the following expression guaranteed to be true?
l == (long) d
I should think no, because as numbers get larger, the gaps between two doubles grow beyond 1 and therefore the conversion back yields a different long value. In case the conversion does not take the value that's greater than the long value, this might also happen earlier.
Is there a definitive answer to that?
Nope, absolutely not. There are plenty of long values which aren't exactly representable by double. In fact, that has to be the case, given that both types are represented in 64 bits, and there are obviously plenty of double values which aren't representable in long (e.g. 0.5)
Simple example (Java and then C#):
// Java
class Test {
public static void main(String[] args) {
long x = Long.MAX_VALUE - 1;
double d = x;
long y = (long) d;
System.out.println(x == y);
}
}
// C#
using System;
class Test
{
static void Main()
{
long x = long.MaxValue;
double d = x;
long y = (long) d;
Console.WriteLine(x == y);
}
}
I observed something really strange when doing this though... in C#, long.MaxValue "worked" in terms of printing False... whereas in Java, I had to use Long.MAX_VALUE - 1. My guess is that this is due to some inlining and 80-bit floating point operations in some cases... but it's still odd :)
You can test this as there are a finite number of long values.
for (long l = Long.MIN_VALUE; l<Long.MAX_VALUE; l++)
{
double d = (double) l;
if (l == (long)d)
{
System.out.println("long " + l + " fails test");
}
}
Doesn't take many iterations to prove that;
l = -9223372036854775805
d = -9.223372036854776E18
(long)d = -9223372036854775808
My code started with 0 and incremented by 100,000,000. The smallest number that failed the test was found to be 2,305,843,009,300,000,000 (19 digits). So, any positive long less than 2,305,843,009,200,000,000 is representable exactly by doubles. In particular, 18-digit longs are also representable exactly by doubles.
By the way, the reason I was interested in this question is that I wondered if I can use doubles to represent timestamps (in milliseconds). Since current timestamps are on the order of 13 digits (and it will take for them rather long time to get to 18 digits), I'll do that.

Categories

Resources