How to store a long value in java dynamically? - java

I was solving a problem on a competitive coding website in java. My code for the problem is:
long arr[]=new long[1000001];
for(int i=2;i<=1000000;i++)
{
arr[i]=arr[i-1]+(i*(i-1));
}
int Test = Integer.parseInt(br.readLine());
for (int i = 0; i < Test; i++) {
int num=Integer.parseInt(br.readLine());
System.out.println(arr[num]);
}
Input
3
1
2
3
4
It is showing correct output as:
0
2
8
20
But when the input is like:
3
10000
100000
1000000
It is showing as:
333333330000
18108503577376
16881588911936
but the output should be:
333333330000
333333333300000
333333333333000000
the last two is wrong.I tried using BigInteger but the time gets exceeded.
However I solved it in python 2.7:
a=[]
a.append(0)
a.append(0)
for i in range(2,1000001):
a.append(a[i-1]+(i*(i-1)));
t=input()
while t:
t-=1
print a[input()]
Input:
Input
3
10000
100000
1000000
Output
333333330000
333333333300000
333333333333000000
Someone please help me how to solve this in Java.
Why is it not showing correct output even if the answer fits into a long?

You're doing most of your calculation with ints, not longs:
arr[i]=arr[i-1]+(i*(i-1));
// ^^^^^^^^^------ All of this is with `int`s
So it overflows the int range before being converted to a long when you add it to arr[i-1].
To avoid overflow, you'll want to cast so you're working with longs earlier:
arr[i]=arr[i-1]+((long)i*(i-1));
// ^^^^^^
Live example

Related

compare the digits of large amount of double values with three constants

i am writing i program to compute the result of a series and compute how many times the result have the same digit of three constant :
example :
//the result is the value of the variable result at each iteration
iteration result
1 3.16661
2 3.16621
3 3.16664
4 3.16661
//what i want is to calculate how many times the variable result had
these digits:
3.16661 ------> 1 //here it is twice
3.166 ------> 4 // all 4 has these digits
3.1666 ------> 3
I thought of storing it as String and compare each char but this insane
my loop is :
for(int i=1; i<400 ; i++) {
result+=Math.pow(-1,i+1)*4.0/(2*i-1);
}
using char will lead to inefficiency and it is a sign of lack of experience
so I am tried to guess I way to do it in an efficient way

Modulus on Combinatorials

Suppose a number n and we have to find sum of all combinatorials of n i.e. nC0+nC1+nC2+...+ nCn.
As result can be large so final answer should be sum%D (D=10^9+7).
Approach I used is-
long sum=0;
long combination=1;
for(int i=1;i<=n;i++){
combination=((combination*(n-i+1))/i)%D;
sum=(sum+combination)%D;
}
But this is not working.
Real Problem statement and code.Code is giving correct output till n=20.
You're supposed to mod the final output, not along every step of the way.
Also the numbers get very large so use BigInteger instead of long.
Here is my solution
http://ide.geeksforgeeks.org/Ew3Epn
Using the formula (2*n)!/(n!)^2
found here -> https://oeis.org/A000984

Java: How to solve a large factorial using arrays?

All the solutions online I can find use BigInteger but I have to solve this using arrays.
I'm only a beginner and I even took this to my Computer Science club and even couldn't figure it out.
Every time I enter a number greater than 31, the output is always zero.
Also, when I enter a number greater than 12, the output is always incorrect.
E.g. fact(13) returns 1932053504 when it should return 6227020800
Here's what I have so far:
import java.util.Scanner;
class Fact
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the number you wish to factorial");
int x = kb.nextInt();
System.out.println(fact(x));
}
public static int fact(int x)
{
int[] a = new int[x];
int product = 1;
for(int i = 0; i < a.length; i++)
{
a[i] = x;
x--;
}
for(int i = 0; i < a.length; i++)
{
product = product * a[i];
}
return product;
}
}
Maximum Values Make Large Numbers Terrible
Sadly, because of the maximum values of integers and longs, you are unable to go any larger than
For Longs:
2^63 - 1
9223372036854775807
9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807
and For Ints:
2^31 - 1
2147483647
2 billion 147 million 483 thousand 647
(I put the written names in to show the size)
At any point in time during the calculation you go over these, "maximum values," you will overflow the variable causing it to behave differently than you would expect, sometimes causing weird zeros to form.
Even BigIntegers have problems with this although it can go up to numbers way higher than just longs and ints which is why they is used with methods that generate massive numbers like factorials.
You seem to want to avoid using BigInteger and only use primatives so long will be the largest data type that you can use.
Even if you convert everything over to long (except the array iterators of course), you will only be able to calculate the factorial up to 20 accurately. Anything over that would overflow the variable. This is because 21! goes over the "maximum value" for longs.
In short, you would need to either use BigInteger or create your own class to calculate the factorials for numbers greater than 20.

Custom number in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to create a custom number class in java, which after ranging from 000000 to 099999 would continue with 0A0000. So the last number would be 9Z9999.
I'm a bit lost on how I could implement this in Java. I suppose I would need to create a custom class which extends Number.
My goal would be to create a class on which I could iterate through (from 000000 to 9Z9999) to reserve document ID ranges.
Although I could do achieve this end with several other workarounds, I find this to be the cleanest solution.
Thank you for any help in advance.
This seems to work. Just use an ordinary number and format it:
static String asStrangeNumber ( int i ) {
// Lowest 4 digits are decimal.
int low4 = i%10000;
i /= 10000;
// Next is base 36 - 0-9-A-Z
int c = i % 36;
i /= 36;
// Remaining should be < 10.
return String.format("%1d%c%04d", i%10, c < 10 ? '0' + c: 'A' + c - 10, low4);
}
public void test() {
test (0);
test (1);
test (10);
test (100);
test (1000);
test (10000);
test (100000);
test (1000000);
}
private void test(int i) {
System.out.println(" "+i+" -> "+asStrangeNumber(i));
}
prints
0 -> 000000
1 -> 000001
10 -> 000010
100 -> 000100
1000 -> 001000
10000 -> 010000
100000 -> 0A0000
1000000 -> 2S0000
I don't think it makes sense. Number defines methods like intValue() etc., and how can you convert 0Z0000 to int?
Just create your own CustomId class, but don't extend Number.
The simplest way to do this is to create a single class that gives out IDs (note these are not numbers per se but words). This would contain 6 counters, each of which had a maximum value (9 for 5 of them 36 for the remaining one that has numbers and letters).
When each new ID is requested the bottom counter is increased, when it reaches it's maximum value it resets to zero and increases the next counter by one etc etc. (this counter could be its own class, with fields for currentValue and maximumValue and method increment() that increments the internal value and returns a boolean as to if the higher counter should be incremented)
Then the actual ID is outputted as a String, with each counter having it's current value converted to a single character (0-9 -->'0'-'9' 10-36 --> 'A'-'Z')

Why do these two similar pieces of code produce different results?

I've been experimenting with Python as a begninner for the past few hours. I wrote a recursive function, that returns recurse(x) as x! in Python and in Java, to compare the two. The two pieces of code are identical, but for some reason, the Python one works, whereas the Java one does not. In Python, I wrote:
x = int(raw_input("Enter: "))
def recurse(num):
if num != 0:
num = num * recurse(num-1)
else:
return 1
return num
print recurse(x)
Where variable num multiplies itself by num-1 until it reaches 0, and outputs the result. In Java, the code is very similar, only longer:
public class Default {
static Scanner input = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter: ");
int x = input.nextInt();
System.out.print(recurse(x));
}
public static int recurse(int num){
if(num != 0){
num = num * recurse(num - 1);
} else {
return 1;
}
return num;
}
}
If I enter 25, the Python Code returns 1.5511x10E25, which is the correct answer, but the Java code returns 2,076,180,480, which is not the correct answer, and I'm not sure why.
Both codes go about the same process:
Check if num is zero
If num is not zero
num = num multiplied by the recursion of num - 1
If num is zero
Return 1, ending that stack of recurse calls, and causing every returned num to begin multiplying
return num
There are no brackets in python; I thought that somehow changed things, so I removed brackets from the Java code, but it didn't change. Changing the boolean (num != 0) to (num > 0 ) didn't change anything either. Adding an if statement to the else provided more context, but the value was still the same.
Printing the values of num at every point gives an idea of how the function goes wrong:
Python:
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
51090942171709440000
1124000727777607680000
25852016738884976640000
620448401733239439360000
15511210043330985984000000
15511210043330985984000000
A steady increase. In the Java:
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
1932053504
1278945280
2004310016
2004189184
-288522240
-898433024
109641728
-2102132736
-1195114496
-522715136
862453760
-775946240
2076180480
2076180480
Not a steady increase. In fact, num is returning negative numbers, as though the function is returning negative numbers, even though num shouldn't get be getting below zero.
Both Python and Java codes are going about the same procedure, yet they are returning wildly different values. Why is this happening?
Two words - integer overflow
While not an expert in python, I assume it may expand the size of the integer type according to its needs.
In Java, however, the size of an int type is fixed - 32bit, and since int is signed, we actually have only 31 bits to represent positive numbers. Once the number you assign is bigger than the maximum, it overflows the int (which is - there is no place to represent the whole number).
While in the C language the behavior in such case is undefined, in Java it is well defined, and it just takes the least 4 bytes of the result.
For example:
System.out.println(Integer.MAX_VALUE + 1);
// Integer.MAX_VALUE = 0x7fffffff
results in:
-2147483648
// 0x7fffffff + 1 = 0x800000000
Edit
Just to make it clearer, here is another example. The following code:
int a = 0x12345678;
int b = 0x12345678;
System.out.println("a*b as int multiplication (overflown) [DECIMAL]: " + (a*b));
System.out.println("a*b as int multiplication (overflown) [HEX]: 0x" + Integer.toHexString(a*b));
System.out.println("a*b as long multiplication (overflown) [DECIMAL]: " + ((long)a*b));
System.out.println("a*b as long multiplication (overflown) [HEX]: 0x" + Long.toHexString((long)a*b));
outputs:
a*b as int multiplication (overflown) [DECIMAL]: 502585408
a*b as int multiplication (overflown) [HEX]: 0x1df4d840
a*b as long multiplication (overflown) [DECIMAL]: 93281312872650816
a*b as long multiplication (overflown) [HEX]: 0x14b66dc1df4d840
And you can see that the second output is the least 4 bytes of the 4 output
Unlike Java, Python has built-in support for long integers of unlimited precision. In Java, an integer is limited to 32 bit and will overflow.
As other already wrote, you get overflow; the numbers simply won't fit within java's datatype representation. Python has a built-in capability of bignum as to where java has not.
Try some smaller values and you will see you java-code works fine.
Java's int range
int
4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type.
Here the range of int is limited
The problem is very simple ..
coz in java the max limit of integer is 2147483647 u can print it by System.out.println(Integer.MAX_VALUE);
and minimum is System.out.println(Integer.MIN_VALUE);
Because in the java version you store the number as an int which I believe is 32-bit. Consider the biggest (unsigned) number you can store with two bits in binary: 11 which is the number 3 in decimal. The biggest number that can be stored four bits in binary is 1111 which is the number 15 in decimal. A 32-bit (signed) number cannot store anything bigger than 2,147,483,647. When you try to store a number bigger than this it suddenly wraps back around and starts counting up from the negative numbers. This is called overflow.
If you want to try storing bigger numbers, try long.

Categories

Resources