Why does this work only up to n=90 or so?
Trying to calculate the 94th fibonacci number gives the incorrect result.
Same thing happens if I use the Integer class instead of Long.
import java.util.HashMap;
public class FDP {
private static HashMap<Long, Long> fib = new HashMap<Long, Long>();
private static Long calculateFib(Long n) {
if(fib.get(n)==null){
Long temp = calculateFib(n-1) + calculateFib(n-2);
fib.put(n, temp);
return temp;
}
else{
return fib.get(n);
}
}
}
public static void main(String[] args) {
fib.put(0L, 0L);
fib.put(1L, 1L);
System.out.println(calculateFib(90L)); //success
System.out.println(calculateFib(94L)); //garbage??
}
}
here is a list of the Fibonacci numbers:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Its an overflow.
The 94th Fibonacci number is: 19740274219868223167
Long.MAX_VALUE is:
9223372036854775807
19740274219868223167 - 9223372036854775807 > 0
You can use BigInteger to handle numbers with arbitrary length.
You reach the limitations of the type Long (64bit), use BigInteger instead
Related
How to put the results of this if condition in a array list?
import java.util.ArrayList;
import java.util.Scanner;
public class GreatestCommonDivisor {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a value whose GCD to be computed");
int number = scan.nextInt();
for(int i=1;i<=10;i++) {
if(number%i==0) {
ArrayList<Integer> arr = new ArrayList<Integer>(number) {
}
}
}
}
}
GCD stands for Greatest Common Divisor...which finds the greatest number that divides all the numbers that you specify, but in your code I just see one number.
So from your code I get the idea that you wish to find all the numbers less than 10 (inclusive) that divide number and store those numbers in an arraylist. Assuming my assumption to be correct you can do the following.
Declare your arraylist before the loop:
ArrayList<Integer>arr = new ArrayList<Integer>()
Now run the loop:
for(int i=1;i<=10;i++){
if(number%i==0){
v.add(i);
}
}
I want to create a method that calculates multiplication of an integer and a bigdecimal. I search on Google and forums, but I didn't find anything.
import java.math.BigDecimal;
private Integer quantite;
private BigDecimal prixUnit;
public Integer getQuantite() {
return quantite;
}
public void setQuantite(Integer quantite) {
this.quantite = quantite;
}
public BigDecimal getPrixUnit() {
return prixUnit;
}
public void setPrixUnit(BigDecimal prixUnit) {
this.prixUnit = prixUnit;
}
public BigDecimal methCal(BigDecimal quantite, BigDecimal prixUnit) {
this.prixUnit=prixUnit;
BigDecimal j = new BigDecimal(quantite);
this.j = quantite;
return quantite*prixUnit;
}
How can I fix this?
To multiply an integer (or byte/short/float/double) with a BigInteger (or BigDecimal), you must convert the native number to BigInteger/BigDecimal first.
// int parameter can be int or Integer
public static BigInteger multiply ( int a, BigInteger b ) {
return BigInteger.valueOf( a ).multiply( b );
}
// BigInteger <> BigDecimal
public static BigDecimal multiply ( int a, BigDecimal b ) {
return BigDecimal.valueOf( a ).multiply( b );
}
// same for add, subtract, divide, mod etc.
Note: valueOf is not the same as new, and for different reasons on BigDecimal and BigInteger.
In both cases, I recommend valueOf over new.
I see that you added your code, nice.
It doesn't work because Integer is mixed with BigDecimal, and also * does not work with BigDecimal.
If you compare it with my code, the fix should be obvious:
public BigDecimal methCal ( int quantite, BigDecimal prixUnit ) {
return BigDecimal.valueOf( quantite ).multiply( prixUnit );
}
Google definitely could have helped you, if you know what to look for:
https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html#BigDecimal-int-
This is one of the constructors for BigDecimal, which allows you to do the following:
BigDecimal five = BigDecimal.valueOf(5);
BigDecimal seven = BigDecimal.valueOf(2).add(five);
Seeing as you stated you wanted to multiply an int and a BigDecimal, this would be achieved as follows:
BigDecimal result = yourBigDecimal.multiply(BigDecimal.valueOf(yourInt));
And, supposing you want this result as an int:
int intResult = result.intValue();
Keep in mind that this throws away the fraction though. If you want rounding instead:
int intResult = result.round(0, RoundingMode.HALF_UP).intValue();
Try this:
import java.math.*;
public class calculator {
public static void main(String[] args) {
BigDecimal value1 = new BigDecimal("3383878445");
BigDecimal returnValue = calculation(2, value1);
System.out.println("value is:" + returnValue);
}
public static BigDecimal calculation(int no1, BigDecimal no2) {
BigDecimal value = BigDecimal.valueOf(no1).multiply(no2);
return value;
}
}
These methods from the Java API will be helpful.
public BigDecimal multiply(BigDecimal multiplicand)
Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
Parameters:
multiplicand - value to be multiplied by this BigDecimal.
Returns:
this * multiplicand
public BigDecimal(int val)
Translates an int into a BigDecimal. The scale of the BigDecimal is zero.
Parameters:
val - int value to be converted to BigDecimal.
Since Java doesn't allow to return two types in one method, I thought best way to do it is to use get methods.
Simply, I wanted computer to generate two random numbers, and if they were not the same I wanted it to print sum of them. If they were the same, I wanted it to roll once more and sum all of the rolls. Until here, it was okay, but then I wanted to see not only sum, but also the numbers that computer generated randomly before adding them up. Therefore, it had to be several return types.
But it prints 0 three times instead.
Can you help me with this? I want to learn what is wrong exactly with this code and if it can be done neater and cleaner? I know Java loves long ways..
Thank you.
class App {
public static int monopolyRoll(int side) {
double randomNumber = Math.random();
randomNumber = randomNumber * side;
randomNumber = randomNumber + 1;
int randomInt = (int) randomNumber;
return randomInt;
}
private int roll1 = monopolyRoll(6);
private int roll2 = monopolyRoll(6);
public int userRolls() {
if (roll1 != roll2) {
return roll1 + roll2;
} else {
int roll3 = monopolyRoll(6);
int roll4 = monopolyRoll(6);
return roll1 + roll2 + roll3 + roll4;
}
}
private static int first;
private static int second;
private static int third;
public App(int first, int second, int third) {
App.first = roll1;
App.second = roll2;
App.third = userRolls();
}
public static int getFirst() {
return first;
}
public static int getSecond() {
return second;
}
public static int getThird() {
return third;
}
public static void main(String[] args) {
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Math.random() works, but you never actually call it in your application. This is what your application does:
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
That's it. Aside from the single return statements in those getter methods and the declared-but-never-assigned integers they return (so, zeroes), none of that other code ever executes.
I suspect this is coming from a bit of a misunderstanding on your part about the static keyword. By sprinkling around the static keyword until the code compiled, what you've done is create something that's syntactically correct but doesn't do anything :)
As a bit of a learning exercise, try moving all of the business logic out of the App class, leaving only the main() method as the application's entry point. And removing all static keywords from the new class you create. This should make the use of that class more clear.
Something like:
class Roller {
private int roll1;
private int roll2;
// other private variables
private int monopolyRoll(int side) {
// your code
}
// your other methods, also private and non-static
public Roller(int first, int second, int third) {
this.first = roll1;
this.second = roll2;
this.third = userRolls();
}
// and so on
}
The idea here is to make things instance-based (non-static) by default. Also make things private by default until explicitly needed to be accessed outside the class. Currently the only things your class needs to expose publicly are the constructor and the getters.
Then in the main() method you'll need to create an instance of your class to use it. Something like this:
Roller roller = new Roller(1, 2, 3);
int first = roller.getFirst();
int second = roller.getSecond();
int third = roller.getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
The answer returned by the following Java code is 0. Can anyone help me find the error?
public class ComplexityOrder {
public static void main(String[] args) {
ComplexityOrder co = new ComplexityOrder();
co.Order(1000);
}
public double Order(int n) {
int[] a = new int[10];
a[0] = Fact(n);
System.out.println("Factorial " + a[0]);
return a[0];
}
public static int Fact(int n) {
if (n == 0 || n ==1) {
return 1;
} else {
return n * Fact(n - 1);
}
}
}
The max value int can contain is 2^32 and 1000! is too big for int to contain it. You can use java.math.BigInteger for the purpose. The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold. There are, however, some practical limits, dictated by the memory available.
Using BigInteger your code will somewhat look like:
import java.math.BigInteger;
public class ComplexityOrder {
public static void main(String[] args) {
ComplexityOrder co = new ComplexityOrder();
co.Order(1000);
}
public BigInteger Order(int n) {
BigInteger[] a = new BigInteger[10];
a[0] = fact(n);
System.out.println("Factorial " + a[0]);
return a[0];
}
public static BigInteger fact(int n) {
if (n == 0 || n ==1) {
return BigInteger.ONE;
} else {
return fact(n-1).multiply(BigInteger.valueOf(n));
}
}
}
Also, I don't see any point using the array.
that is because of the overflow of int variable that maximum contain number = 2^32 , and Fact(1000) is more than Max int, if you don't acquire numbers leas than 100 you can use BigInteger class instead of int , if you acquire big numbers you have to implement your string addition function to avoid overflow .
To be more specific ...
You are using standard integers, an n-bit signed binary number. You then compute 1000! This is a very large number compared to any standard integer representation. The prime factorization includes 2^994. This means that the resulting number, in binary, ends with a string of 994 zeroes.
When integer overflow isn't handled as an exception, the condition is a highly informal way of reducing your result mod 2^n, where n is the length of the internal representation, usually 32 or 64 bits, and then mapping the higher half of the range to negative numbers. A number that ends in at least n zeroes will get reduced to 0 (mod 2^n). That's what happened in your case, as your computer does not have 1024-bit integers. :-)
As others have already suggested, you can handle this capacity by switching to BigInteger and adjusting your class to deal with the expanded range. Do note that it will be much slower, as you are beyond the hardware's native integer range, and the processing resembles doing all operations by hand in base 2^n. "Write down the 00110111001010010110110001010110, carry the 1, and on to the next column." :-)
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.
Of course, it's trivial to implement it manually:
import java.util.LinkedList;
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
super.add(o);
while (size() > limit) { super.remove(); }
return true;
}
}
As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:
CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.
Update: updated answer following release of commons collections version 4 that supports generics.
Guava now has an EvictingQueue, a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.
import java.util.Queue;
import com.google.common.collect.EvictingQueue;
Queue<Integer> fifo = EvictingQueue.create(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
I like #FractalizeR solution. But I would in addition keep and return the value from super.add(o)!
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
}
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).
To my knowledge your trivial implementation is the easiest way to get such an behaviour.
You can use a MinMaxPriorityQueue from Google Guava, from the javadoc:
A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.
An LRUMap is another possibility, also from Apache Commons.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html
Ok I'll share this option. This is a pretty performant option - it uses an array internally - and reuses entries. It's thread safe - and you can retrieve the contents as a List.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
synchronized void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
int c = cur
int s = size
T[] e = entries.collect() as T[]
List<T> list = new ArrayList<>()
int oldest = (c == s - 1) ? 0 : c
for (int i = 0; i < e.length; i++) {
def entry = e[oldest + i < s ? oldest + i : oldest + i - s]
if (entry) list.add(entry)
}
return list
}
}
public class ArrayLimitedQueue<E> extends ArrayDeque<E> {
private int limit;
public ArrayLimitedQueue(int limit) {
super(limit + 1);
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
#Override
public void addLast(E e) {
super.addLast(e);
while (size() > limit) {
super.removeLast();
}
}
#Override
public boolean offerLast(E e) {
boolean added = super.offerLast(e);
while (added && size() > limit) {
super.pollLast();
}
return added;
}
}