Working with really big numbers - java

please have a look at the following code
import java.util.ArrayList;
import java.util.List;
public class Big
{
static int primeNumber = 2;
public static void main(String[]args)
{
int numberDevident = 147;
int left=0;
int result=0;
List numbers = new ArrayList();
while(true)
{
result = numberDevident/primeNumber;
left = numberDevident%primeNumber;
if(left!=0)
{
primeNumber++;
}
else
{
numbers.add(primeNumber);
numberDevident = result;
System.out.println(primeNumber);
}
}
}
}
This code find the prime factors of a given number (Variable "numberDevident" in the code"). But, there is a case, that is, the given number is 600851475143
It is no way matching to int, long or double. How can I solve this using this much of a big number? Please help
Here I am doing the same with BigInteger
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class Problem3
{
static BigInteger primeNumber = new BigInteger("2");
static BigInteger zero = new BigInteger("0");
static BigInteger add = new BigInteger("1");
public static void main(String[]args)
{
BigInteger numberDevident = new BigInteger("147");
BigInteger left= new BigInteger("0");;
BigInteger result=new BigInteger("0");;
List numbers = new ArrayList();
while(true)
{
result = numberDevident.divide(primeNumber);
left = numberDevident.remainder(primeNumber);
if(left!=zero)
{
primeNumber.add(add);
}
else
{
numbers.add(primeNumber);
numberDevident = result;
System.out.println(primeNumber.toString());
}
}
}
}
still no good, it is not displaying anything. Please help.

You might want to take a look at BigInteger.

Related

Big Integer Java

Why is my code printing the output 4 times? The answer is correct but the answer is printed 4 times instead of the desired one time.
import java.util.*;
import java.math.BigInteger;
class THIRTYSEVEN
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
BigInteger a = new BigInteger("1");
multiply(a,0,sc.nextInt());
}
static void multiply(BigInteger b, int loop, int power)
{
BigInteger result = b;
while(loop<power)
{
result = result.multiply(new BigInteger("8"));
loop++;
multiply(result,loop,power);
}
System.out.println(result);
}
}
You call multiplyonly once, but it recursively calls itself (and prints every time). You could return the result instead (and print it from main).

find all combinations of given numbers in a given array size

I need to find all combinations from size n that consists of the numbers in numbers array. I tried to do it with the function I wrote below but it takes a lot of time and memory to do it like that.
Is there a way to do it more efficient?
void createCombinationArray(ArrayList<Integer> numbers, int n, ArrayList<Integer> start) {
if (start.size() >= n) {
monthsComb.add(new ArrayList<>(start));
} else {
for (Integer x : numbers) {
start.add(x);
createCombinationArray(numbers, n, start);
start.remove(start.lastIndexOf(x));
}
}
}
One way to do it more efficently (both for time and memory) is to store the result as int[][] instead of Collection<List<Integer>> (which I assume to be the type of the monthsComb field). You can do this because you know that if you have k numbers the result will be Binomial(n, k) combinations of n numbers.
Another way (as #Phia-CM suggested) would be to implement a non-recoursive version of the algorithm.
I know they are both uneasy to implement, but that's the way for efficiency.
Ask yourself whether you really need to generate all of these lists ahead of time. Maybe it would be acceptable to generate them on demand.
Keep in mind that each of these lists can be represented by a number with numbers.length bits, n or more of which are set. You could work with a data structure of this sort to reference a list external to it.
It would be quite straightforward to write a List implementation with this behavior.
import java.util.BitSet;
import java.util.List;
public class SelectiveList<T> implements List<T> {
private final BitSet bitSet;
private final List<T> list;
public SelectiveList(BitSet bitSet, List<T> list) {
this.bitSet = bitSet;
this.list = list;
}
#Override
public T get(int index) {
return list.get(nthOnBit(index));
}
private int nthOnBit(int n) {
int onBits = 0;
int i;
for (i = bitSet.nextSetBit(0); i >= 0 && onBits < n; i = bitSet.nextSetBit(i + 1)) {
onBits++;
}
if (onBits < n) {
throw new IllegalArgumentException();
}
return i;
}
// etc.
}
You may try this:
package combination;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Combination implements Iterator<List<Integer>> {
public Combination(final List<Integer> numbers, final int n) {
this.numbers = numbers;
this.n = n;
this.current = BigInteger.valueOf(0);
this.radix = BigInteger.valueOf(numbers.size());
this.size = this.radix.pow(n);
}
#Override
public final boolean hasNext() {
return this.current.compareTo(size) < 0;
}
#Override
public final List<Integer> next() {
List<Integer> result = new ArrayList(this.n);
BigInteger value = this.current;
for(int i=0; i<n; i++) {
result.add(i, this.numbers.get(
value.mod(this.radix).intValueExact()));
value = value.divide(this.radix);
}
this.current = this.current.add(BigInteger.valueOf(1));
return result;
}
private final List<Integer> numbers;
private final int n;
private BigInteger current;
private final BigInteger size;
private final BigInteger radix;
public static void main(String[] args) {
Combination cb = new Combination(Arrays.asList(0, 2, 4, 6), 3);
while (cb.hasNext()) {
System.out.println(cb.next());
}
}
}

how to use BigInt for a modified Fibonacci

I am trying to solve this: problem
And by Dynamic programming I am able to solve the problem, here is the code so far:
import java.util.Scanner;
public class Dy
{
static long[] storage = new long[20];
public static void main(String[] args)
{
Scanner sx = new Scanner(System.in);
storage[0] = sx.nextInt();
storage[1] = sx.nextInt();
int x = sx.nextInt();
System.out.println(beast(x-1));
}
public static long beast(int n)
{
if(n==0)
return storage[n];
if(n==1)
return storage[n];
if(storage[n]!=0)
return storage[n];
storage[n] = (beast(n-1)*beast(n-1)) + beast(n-2);
return storage[n];
}
}
But the real trouble here is , if n is say around 20, even long data type won't hold the value, so the choice is obviously BigInteger , but as a learner, I was wondering how to use BigInteger with Arrays in Java? Any help will be much appreciated, thanks!
You could use a Map<Integer, BigInteger> and something like,
static Map<Integer, BigInteger> storage = new HashMap<>();
public static void main(String[] args) {
Scanner sx = new Scanner(System.in);
// Add 0 and 1.
storage.put(0, BigInteger.valueOf(sx.nextInt()));
storage.put(1, BigInteger.valueOf(sx.nextInt()));
int x = sx.nextInt();
System.out.println(beast(x - 1));
}
public static BigInteger beast(int n) {
if (!storage.containsKey(n)) {
BigInteger t = beast(n - 1);
storage.put(n, t.multiply(t).add(beast(n - 2)));
}
return storage.get(n);
}

NZEC Prime number Generation SPOJ- http://www.spoj.com/problems/PRIME1/

I am beginner at coding. I am getting NZEC error on submission of my code for prime number genertaion to spoj. But the code is working perfectly fine in my desktop. Kindly help me. This is what i have coded.
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int testcase;
int lower_limit,upper_limit;
int i,j,k;
boolean[] a= new boolean[100001];
Arrays.fill(a, Boolean.TRUE);
Scanner sc1 = new Scanner(System.in);
testcase= sc1.nextInt();
for(;testcase>0;testcase--)
{
lower_limit= sc1.nextInt();
upper_limit= sc1.nextInt();
for(i = 2;i<sqrt(upper_limit);i++)
{
if(a[i]=true)
{
for(j=i;j<=upper_limit;j=j+i)
{
a[j]=false;
}
}
}
for(i=lower_limit;i<upper_limit;i++)
{
if(a[i]==true)
{
System.out.println(i);
}
}
}
}
}
Your array goes out of index for large values of m and n. Try this sample test case on your system where m = 999900000 and n = 1000000000. You can't store these large values as the index of the array. Even m or n = 10^8 will go out of bound index for an array.

Recursive depth first search Integer ArrayList Java

What I'm trying to do is essentially look at a set of numbers, and find all subsets of those numbers and eventually print them out. I'm completely stuck on writing the recursion method. The idea is to use a Boolean arraylist as a form of a tree, and traverse through it testing all the different sums for what I'm looking for. The problem is that it's not even going through the tree correctly, so any suggestions would be of great help.
package programmingassignment3;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubsetSum {
public ArrayList<Integer> set1 = new ArrayList<Integer>(Arrays.asList(1,2,3,4));
int d = 6;
public void test(){
Collections.sort(set1);
for(int i =0;i<set1.size();i++)
if(set1.get(i)>d)
set1.remove(i);
ArrayList<Boolean> set1test = new ArrayList();
recSubSetSum(set1test);
}
public void recSubSetSum(ArrayList<Boolean> subsetList)
{
if(sumOfList(subsetList)>=d)
System.out.println("Output Set(WIP)");
ArrayList<Boolean> leftList = new ArrayList();
ArrayList<Boolean> rightList = new ArrayList();
for(int i =0;i<set1.size();i++)
{
leftList = new ArrayList(subsetList);
rightList = new ArrayList(subsetList);
if(set1.size()>leftList.size())
leftList.add(true);
if(set1.size()>rightList.size())
rightList.add(false);
if(sumOfList(leftList)<d)
{
recSubSetSum(leftList);
if(set1.size()>rightList.size())
rightList.add(false);
}
if(sumOfList(rightList)<d)
recSubSetSum(rightList);
}
}
public int sumOfList(ArrayList<Boolean> subSetList)
{
int sum = 0;
for(int i = 0;i<subSetList.size();i++)
{
if(subSetList.get(i))
sum+=set1.get(i);
}
return sum;
}
}

Categories