Java: How to solve a large factorial using arrays? - java

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.

Related

Java Random.nextInt() behavior

I wrote this simple code just out of curiosity and encountered some behavior of the nextInt() method from the Java Random class that I don't quite understand. Can anyone help me to figure it out?
The program simulates a simple coin flipping. So as far as I understand the probability of the nextInt(101) for numbers less and greater than 49 should be equal.
But as long as I increase the number of iterations, the balance tends to get positive, for example after 100,000 iterations, I didn't get a negative number. Why does this happen?
public static void main(String[] args) {
int balance = 0;
for (int i = 0; i < 100000; i++) {
Random random = new Random();
int result = random.nextInt(101);
if (result > 49) {
balance++;
} else {
balance--;
}
}
System.out.println("Player's balance = " + balance);
}
You call int result = random.nextInt(101) which creates uniformly distributed integers in [0,100], which can take 101 different values. If you check if (result > 49) then you have 51 possible values ([50,100]) and in the else case you have only 50 values ([0,49]). Thus the result is more likely to be in the upper part. To fix it you can do int result = random.nextInt(100).
you are testing 51 possibilities for a positive outcome and only 50 possibilities for a negative outcome.
100-50 = 51 possibilities
0-49 = 50 possibilities.
If you have tried, random.nextInt(99), result will be different, I got minus value many times.
The reason behind this is that random.nextInt() Method.
quoted from the JavaDoc.
The algorithm is slightly tricky. It rejects values that would result
in an uneven distribution (due to the fact that 2^31 is not divisible
by n). The probability of a value being rejected depends on n. The
worst case is n=2^30+1, for which the probability of a reject is 1/2,
and the expected number of iterations before the loop terminates is 2.
Please see here Random.java#nextInt(int)

Sum of Absolutes

I was trying to solve the simple problem posted on HackerRank.
https://www.hackerrank.com/contests/w16/challenges/sum-of-absolutes
I solved the problem, however its getting time out error to those with input array of size 100000. Could someone help me optimize this code below so it does not timeout.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print outputto STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int q = in.nextInt();
in.nextLine();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)
{
a[i]= in.nextInt();
}
for(int j=0;j<q;j++)
{
int l = in.nextInt();
int r = in.nextInt();
int sum=0;
for(int k=l;k<=r ;k++)
{
sum = Math.abs(sum+a[k]);
}
if(sum%2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}
}
I think you need to completely rethink your solution: You don;t actually need to work out the summation in order to establish if the result is odd or even.
The observation that adding two even numbers or two odd number gives you an even; and that adding an even and an odd give you an odd for all numbers (positive and negative) should be all you need.
Think about whether there's a shortcut that will give you the same odd/even answer. For example, -8 and 8 are both even while -3 and 3 are both odd. Do you really need to take an absolute value to determine if the sum is even or odd?
---Edit: Another thought or two---
First thought.
Please take a look at Bitwise and Bit Shift Operations. There are bitwise ways to figure out if the number is negative (namely: The high-order bit is 1). And there are bitwise ways to tell if the number is odd (namely: The low-order bit of a positive number is 1 and the low order bit of a negative number is 0).
--- Edit: Second thought---
Could you compress the array by not storing the input numbers, but instead the parity of those numbers? For example, you could use boolean[] isOdd or BitSet isOdd? You could store -7 in position i as isOdd[i] = true; or isOdd.set(i);. (Since BitSet and boolean both initialize to all false, you would not change the boolean or BitSet in position j if position j were even; see BitSet.) Then your answer would consist of counting the odds (or flipping a boolean or not'ing a bit) in the requested set and answering odd if the sum were odd (or false or 0) or even if the sum were even (or true or 1).
Why should you use a BitSet or boolean array? You can pack more information into less memory, making it easier for Java to find the space and leading to fewer page faults should you go over a page boundary.
I'm going to give you two hints. First, always look for needlessly repeated operations (spoiler: how many times do you do Math.abs on each value in the set?). And second, file IO is very expensive. Look for a way to use Scanner more efficiently.

Project Euler #8 in java

The challenge is listed here:
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
I have written a code that works with the given 4 digit example, but doesn't work for 13 digits. I suspect there is some type of data overflow, but I am unsure. My super inefficient code is below.
public class Euler8 {
public static void main(String[]args){
String num = "/*number listed above*/";
int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13;
long sum=0, newSum;
for(int n=0; n<=987; n++){
n1=Character.getNumericValue(num.charAt(n));
n2=Character.getNumericValue(num.charAt(n+1));
n3=Character.getNumericValue(num.charAt(n+2));
n4=Character.getNumericValue(num.charAt(n+3));
n5=Character.getNumericValue(num.charAt(n+4));
n6=Character.getNumericValue(num.charAt(n+5));
n7=Character.getNumericValue(num.charAt(n+6));
n8=Character.getNumericValue(num.charAt(n+7));
n9=Character.getNumericValue(num.charAt(n+8));
n10=Character.getNumericValue(num.charAt(n+9));
n11=Character.getNumericValue(num.charAt(n+10));
n12=Character.getNumericValue(num.charAt(n+11));
n13=Character.getNumericValue(num.charAt(n+12));
newSum= (long)(n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13);
if(newSum>=sum)
sum=newSum;
}
System.out.println(sum);
}
}
My code outputs this number:
2091059712
Your code makes a cast to long too late: by the time the cast is performed, the multiplication has been completed in 32-bit integers, predictably causing an overflow.
Change the code as follows to fix the problem:
// newSum should be called newProd, because you use multiplication, not addition
newSum= ((long)n1)*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13;
Note that your algorithm is not the most efficient: you could do it 13 times faster if you observe that the product for positions i+1..i+13 can be computed from the product for positions i..i+12 by dividing the value at position i and multiplying by the value at position i+13.
Of course you would have to be careful not to divide by zero. You can work around this by observing that any time you encounter a zero, the next 13 products would all be zero, so you could simply skip them, and move on to the next "train" of non-zeros.
The problem is that n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13 overflows because:
they are all int variables, and
an int multiplied by an int gives an int.
The typecase to long is applied to the entire product, and (therefore) happens too late to cause the computations to be done with long arithmetic and avoid the overflow problem.
The simple solution to that particular problem is to declare the n variables as long. It is possible that #dasblinkelights' code (casting n1) is faster ... but you would need to benchmark it to be sure. And there are more significant optimizations than that.
I get the answer as 23514624000 . which is actually correct.
public class LargestProduct {
public static void main(String[]args) {
String s="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
long k=0,l=13,ans=1,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13;
long Max_Num=0;
String[] result=new String[1000];
result=s.split("");
for(int i=0;i<=987;i++) {
n1=Integer.parseInt(result[i]);
n2=Integer.parseInt(result[i+1]);
n3=Integer.parseInt(result[i+2]);
n4=Integer.parseInt(result[i+3]);
n5=Integer.parseInt(result[i+4]);
n6=Integer.parseInt(result[i+5]);
n7=Integer.parseInt(result[i+6]);
n8=Integer.parseInt(result[i+7]);
n9=Integer.parseInt(result[i+8]);
n10=Integer.parseInt(result[i+9]);
n11=Integer.parseInt(result[i+10]);
n12=Integer.parseInt(result[i+11]);
n13=Integer.parseInt(result[i+12]);
ans=n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13;
Max_Num=Math.max(Max_Num, ans);
}
System.out.println(Max_Num);
}
}

Unexpected behavior when modifying Fibonacci Sequence Generator

I have been toying around with my program for Exercise 4.10, from the Art and Science of Java Chapter 4 Exercise 10. Here's my code:
import acm.program.*;
public class FibonacciSequenceModified extends ConsoleProgram{
public void run(){
println("This program will display the numbers of the fibonacci sequence that are less than " +
"10,000");
int total=0;
int x=0;
int y=1;
println("F0= "+ x);
println("F1= "+ y);
for (int num=2; num<=100; num++){
total=x+y;
if (total<10000){
println("F" + num +"= " +total);
x=y;
y=total;
}
}
}
}
This program will work and F20=6765 is its last line. However, if I modified the code so that the first curly brace "}" is now before x=y; instead of after y=total;, the program goes bonkers and will display huge negative numbers past F20=6765. Can anyone explain to me what the code is trying to do with this simple alteration?
That curly brace represents the end of the if block, which is preventing your loop for counting Fibonacci numbers after 10000 has been reached. The reason it needs to do this is because Fibonacci numbers grow exponentially, and will eventually be too big for a simple 32 bit int to store.
What is happening is interger overflow. that means that your ints are so big that they can't fit in 32 bits.
as an example, consider the largest 32 bit signed integer: 2,147,483,647
01111111111111111111111111111111
if you add 1 to it, it would become this:
10000000000000000000000000000000
That is smallest negative intger: 2,147,483,648 . your numbers are going beyond that. That's why you're seeing negatives
if you keep "adding" to that, eventually, you'll end up at the following:
11111111111111111111111111111111
That's -1 in Two's compliment representation. if you add 1 to that, you'll get this
100000000000000000000000000000000
you might notice, that there are more than 32 bits there. The most significant bit(the 1) will get truncated, and we're back to 0.
00000000000000000000000000000000
your fibbonacci numbers keep over-shooting this 32 bit limit, since the most significant bits are left off, the remaining bits aren't very meaningful, and that's why you're seeing random-looking numbers.
If you move the } before x=y;, then you are in effect continuing to determine Fibonacci numbers past number 20, but only printing them out if they are less than 10,000. This continues to work until the numbers get so big that they overflow the int datatype you're using to calculate the numbers. The largest int possible is 231 - 1, and the 47th number passes that value. The result is that some of them will be negative because of this overflow. Those negative numbers are less than 10,000 so they are printed.
This behavior is seen more clearly when the if and associated braces are removed completely:
This program will display the numbers of the fibonacci sequence that are less than 10,000
F0= 0
F1= 1
F2= 1
F3= 2
F4= 3
F5= 5
F6= 8
...
F18= 2584
F19= 4181
F20= 6765
F21= 10946
F22= 17711
...
F44= 701408733
F45= 1134903170
F46= 1836311903
F47= -1323752223 <= First negative resulting from overflow.
F48= 512559680
F49= -811192543
F50= -298632863
...
F98= -90618175
F99= -889489150
F100= -980107325
The reason the code as you have it worked is that you only determined the next number if the total is less than 10,000, so you never calculated enough numbers high enough to overflow. Loops where num is 22 and above did nothing.
Once the total is greater than 10,000, you can keep the } before x=y; if you break out of the loop.
if (total<10000){
System.out.println("F" + num +"= " +total);
}
else
{
break;
}
x=y;
y=total;
As an aside, note that changing the datatypes of total, x, and y to long helps, but it only postpones the problem. This will overflow a long at the 93rd term.
F90= 2880067194370816120
F91= 4660046610375530309
F92= 7540113804746346429
F93= -6246583658587674878
F94= 1293530146158671551
F95= -4953053512429003327
F96= -3659523366270331776
F97= -8612576878699335103
F98= 6174643828739884737
F99= -2437933049959450366
F100= 3736710778780434371
BigIntegers would be able to store these huge numbers precisely.
If you have the following code
int total = 0;
int x = 0;
int y = 1;
System.out.println("F0= "+ x);
System.out.println("F1= "+ y);
for (int num = 2; num <= 100; num++){
total = x + y;
if (total < 10000) {
System.out.println("F" + num +"= " +total);
}
x = y;
y = total;
}
What is happening is, the program succesfully calculates the fibonacchi numbers up to F46, but prints only numbers up to F20 due to the statement if (total < 10000) . . . (tested in ideone.com). The 47th fibonacchi number exceeds the maximum value of int, thus returning garbage, which is often seen as a negative number. Your program prints all such garbage because it's less than 10,000. The maximum value for int is 2^31 - 1, which is about 2 billion.

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