Method works but throws errors for particular numbers - java

I wrote a method that calculates the combination of 2 numbers and it works for smaller numbers where n = 10 and r = 3, but when input n as 100 and r as 3 it throws an arithmetic exception
" / by zero"
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scan.nextInt();
System.out.print("\nEnter r: ");
int r = scan.nextInt();
scan.close();
int ans = factorial(n) / (factorial((n-r)) * factorial(r));
System.out.print("\nThe combination is: "+ans);
}
static int factorial(int num) {
for(int i = num; i>1; --i) {
num *= (i - 1);
}
return num;
}
}
but i don't know what the problem is. it works for smaller numbers of n.

You're multiplying values which result in a number too big to fit inside an integer.
If you print out the num inside your for loop, you'll notice it eventually either goes negative or to zero. This is due to overflow.
For your example of n=100 and r=3 not even long will do. You'll need to use something like BigInteger.
Keep in mind that using BigInteger will drastically slow down your program when compared to using primitives.
If you're not interested in having such large numbers and were just curious why it wasn't working, you can also use Math.multiplyExact(int x, int y) or Math.multiplyExact(long x, long y) if you're using Java 8 or above.
By using these methods, you'll avoid having to deal with the side-effects of overflow since they will throw an ArithmeticException if the result overflows.

Change the data type of num from int to double

Related

Java Euler number result infinity

I try to use a recursive function to calculate the Euler number in Java. It's OK when I enter small numbers into this formula:
But when I try to enter a bigger number like 1000 I get infinity.
Why it's happening. How I can fix it.
import java.util.Scanner;
public class enumber {
public static long fact(int a) {
if(a <= 1) {
return 1;
}
return a * fact(a - 1);
}
public static double calculate(int i) {
double cresult = Math.pow(fact(i), -1);
if(i == 0 ) {
return 1;
}
return cresult+calculate(i-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter i value: ");
int i = sc.nextInt();
double eresult = calculate(i);
System.out.println(eresult);
}
}
output;
Enter i value:
1000
Infinity
That's because you try to calculate the factorial of 1000....which is pretty huge.
Factorial 1000
You try to store it in a long value, but long's
max value is way smaller than 1000!. It basically doesn't fit anymore.
Consider using the class BigInteger (or BigDecimal), its in the default java sdk and you can directly output via println().
However you know the result already, its e, so you might only need to implement the Big-Class for the factorial.
You are exceeding the capacity of a long. But I would suggest you decide how much precision you want for e.
Let's say you want it to have an error of less than .0000001. Continue the iteration for e until the positive delta between your latest computation and the previous is less than or equal to your error.
If you want to take it to extremes, you can always use BigDecimal to increase the accuracy of your results.
I solved that problem by using loops. And for the old algorithm, I changed the fact method type to double. I get rid of Infinity. After that, I face "StackOverflowError".
What is a StackOverflowError?
My new algorithm is;
import java.util.Scanner;
public class enumber2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double fact;
double eNumber = 0;
int i = in.nextInt();
while(i>0) {
fact=1;
for(int j=1; j<=i; j++) {
fact = fact * j;
}
eNumber = eNumber +(1.0/fact);
i--;
}
eNumber = eNumber +1;
System.out.println(eNumber);
}
}
even I enter big numbers after a little bit of patient I'm getting results without exception.

Floating point inaccuracy during e calculation with numerical methods

So i was calculating e(third row in picture) with numerical methods.
I was increasing the number of elements i used every iteration. And when i executed the program, floating point variable behaved in a way i didn't understand. Here is the program and the result.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int factorial = 1;
int counter = 0;
int iterationNumber;
double total = 0;
int tempCounter;
System.out.print("Enter iteration number: ");
iterationNumber = input.nextInt();
while (counter <= iterationNumber) {
tempCounter = counter;
while ((tempCounter - 1) > 0) {
factorial *= tempCounter;
tempCounter--;
}
total += ((double)1 / factorial);
System.out.println(total);
factorial = 1;
counter ++;
}
}
}
So my question is why does the value of e starts to decrease after a while instead of increasing? I want to learn how floating point variable behaves during this program and the logic behind it.
Another question is why does it start to say infinity?
n! quickly exceeds Integer.MAX_VALUE and overflows to a negative number. You are then adding a negative number to your total --- thus the decrease.
You can use BigDecimal for your calcualtions. It is slower, but will do the job.

Checking whether a number is in Fibonacci Sequence?

It was asked to find a way to check whether a number is in the Fibonacci Sequence or not.
The constraints are
1≤T≤10^5
1≤N≤10^10
where the T is the number of test cases,
and N is the given number, the Fibonacci candidate to be tested.
I wrote it the following using the fact a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0 ; i < n; i++){
int cand = sc.nextInt();
if(cand < 0){System.out.println("IsNotFibo"); return; }
int aTest =(5 * (cand *cand)) + 4;
int bTest = (5 * (cand *cand)) - 4;
int sqrt1 = (int)Math.sqrt(aTest);// Taking square root of aTest, taking into account only the integer part.
int sqrt2 = (int)Math.sqrt(bTest);// Taking square root of bTest, taking into account only the integer part.
if((sqrt1 * sqrt1 == aTest)||(sqrt2 * sqrt2 == bTest)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
}
But its not clearing all the test cases? What bug fixes I can do ?
A much simpler solution is based on the fact that there are only 49 Fibonacci numbers below 10^10.
Precompute them and store them in an array or hash table for existency checks.
The runtime complexity will be O(log N + T):
Set<Long> nums = new HashSet<>();
long a = 1, b = 2;
while (a <= 10000000000L) {
nums.add(a);
long c = a + b;
a = b;
b = c;
}
// then for each query, use nums.contains() to check for Fibonacci-ness
If you want to go down the perfect square route, you might want to use arbitrary-precision arithmetics:
// find ceil(sqrt(n)) in O(log n) steps
BigInteger ceilSqrt(BigInteger n) {
// use binary search to find smallest x with x^2 >= n
BigInteger lo = BigInteger.valueOf(1),
hi = BigInteger.valueOf(n);
while (lo.compareTo(hi) < 0) {
BigInteger mid = lo.add(hi).divide(2);
if (mid.multiply(mid).compareTo(x) >= 0)
hi = mid;
else
lo = mid.add(BigInteger.ONE);
}
return lo;
}
// checks if n is a perfect square
boolean isPerfectSquare(BigInteger n) {
BigInteger x = ceilSqrt(n);
return x.multiply(x).equals(n);
}
Your tests for perfect squares involve floating point calculations. That is liable to give you incorrect answers because floating point calculations typically give you inaccurate results. (Floating point is at best an approximate to Real numbers.)
In this case sqrt(n*n) might give you n - epsilon for some small epsilon and (int) sqrt(n*n) would then be n - 1 instead of the expected n.
Restructure your code so that the tests are performed using integer arithmetic. But note that N < 1010 means that N2 < 1020. That is bigger than a long ... so you will need to use ...
UPDATE
There is more to it than this. First, Math.sqrt(double) is guaranteed to give you a double result that is rounded to the closest double value to the true square root. So you might think we are in the clear (as it were).
But the problem is that N multiplied by N has up to 20 significant digits ... which is more than can be represented when you widen the number to a double in order to make the sqrt call. (A double has 15.95 decimal digits of precision, according to Wikipedia.)
On top of that, the code as written does this:
int cand = sc.nextInt();
int aTest = (5 * (cand * cand)) + 4;
For large values of cand, that is liable to overflow. And it will even overflow if you use long instead of int ... given that the cand values may be up to 10^10. (A long can represent numbers up to +9,223,372,036,854,775,807 ... which is less than 1020.) And then we have to multiply N2 by 5.
In summary, while the code should work for small candidates, for really large ones it could either break when you attempt to read the candidate (as an int) or it could give the wrong answer due to integer overflow (as a long).
Fixing this requires a significant rethink. (Or deeper analysis than I have done to show that the computational hazards don't result in an incorrect answer for any large N in the range of possible inputs.)
According to this link a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square so you can basically do this check.
Hope this helps :)
Use binary search and the Fibonacci Q-matrix for a O((log n)^2) solution per test case if you use exponentiation by squaring.
Your solution does not work because it involves rounding floating point square roots of large numbers (potentially large enough not to even fit in a long), which sometimes will not be exact.
The binary search will work like this: find Q^m: if the m-th Fibonacci number is larger than yours, set right = m, if it is equal return true, else set left = m + 1.
As it was correctly said, sqrt could be rounded down. So:
Even if you use long instead of int, it has 18 digits.
even if you use Math.round(), not simply (int) or (long). Notice, your function wouldn't work correctly even on small numbers because of that.
double have 14 digits, long has 18, so you can't work with squares, you need 20 digits.
BigInteger and BigDecimal have no sqrt() function.
So, you have three ways:
write your own sqrt for BigInteger.
check all numbers around the found unprecise double sqrt() for being a real sqrt. That means also working with numbers and their errors simultaneously. (it's horror!)
count all Fibonacci numbers under 10^10 and compare against them.
The last variant is by far the simplest one.
Looks like to me the for-loop doesn't make any sense ?
When you remove the for-loop for me the program works as advertised:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cand = sc.nextInt();
if(cand < 0){System.out.println("IsNotFibo"); return; }
int aTest = 5 * cand *cand + 4;
int bTest = 5 * cand *cand - 4;
int sqrt1 = (int)Math.sqrt(aTest);
int sqrt2 = (int)Math.sqrt(bTest);
if((sqrt1 * sqrt1 == aTest)||(sqrt2 * sqrt2 == bTest)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
You only need to test for a given candidate, yes? What is the for loop accomplishing? Could the results of the loop be throwing your testing program off?
Also, there is a missing } in the code. It will not run as posted without adding another } at the end, after which it runs fine for the following input:
10 1 2 3 4 5 6 7 8 9 10
IsFibo
IsFibo
IsFibo
IsNotFibo
IsFibo
IsNotFibo
IsNotFibo
IsFibo
IsNotFibo
IsNotFibo
Taking into account all the above suggestions I wrote the following which passed all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long[] fib = new long[52];
Set<Long> fibSet = new HashSet<>(52);
fib[0] = 0L;
fib[1] = 1L;
for(int i = 2; i < 52; i++){
fib[i] = fib[i-1] + fib[i - 2];
fibSet.add(fib[i]);
}
int n = sc.nextInt();
long cand;
for(int i = 0; i < n; i++){
cand = sc.nextLong();
if(cand < 0){System.out.println("IsNotFibo");continue;}
if(fibSet.contains(cand)){
System.out.println("IsFibo");
}else{
System.out.println("IsNotFibo");
}
}
}
}
I wanted to be on the safer side hence I choose 52 as the number of elements in the Fibonacci sequence under consideration.

print the decimal equivalent of a binary number in java

My code is to print the decimal equivalent of a binary number entered by user.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a binary integer: ");
int b=in.nextInt();
int digits=1;
int q=b;
//determine the number of digits
while(q/10>=1){
++digits;
q/=10;
}
System.out.println(digits);
int decimal=0;
int i=0;
//pick off the binary number's digits and calculate the decimal equivalent
while(i<=digits-1){
decimal+=b/Math.pow(10,i)%10*Math.pow(2,i);
i++;
}
System.out.println(decimal);
}
}
When I enter 1101, it outputs 13, which is the right answer. However, when I
test the number 11001, the decimal equivalent is supposed to be 25, but it outputs 26. I try
to fix it but can't find where the bug is. Can you guys help me out?
The problem is that Math.pow returns a floating-point number, and you're doing floating-point calculations where you think you're doing integer calculations. When i is 4, and you calculate
b/Math.pow(10,i)%10*Math.pow(2,i);
the calculation goes like this:
b = 11001
b / Math.pow(10,i) = b / 10000 = 1.1001 (not 1)
1.1001 % 10 = 1.1001
1.1001 * Math.pow(2,i) = 1.1001 * 16 = 17.6016 (not 16)
This is then cast to an (int) when you add it to decimal. It truncates the last value to 17, but it's too late.
Casting the Math.pow results to an (int) will make it work. But this isn't the right approach anyway. If you want to learn how to do it yourself instead of using parseInt, it's best to input the number as a String (see my earlier comment), and then you don't have to worry about picking off the bits as decimal digits or powers of 10 at all anyway. Even using your approach, instead of Math.pow it would be simpler to keep powerOf10 and powerOf2 integer variables that you modify with powerOf10 *= 10; powerOf2 *= 2; in each loop iteration.
Try using:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a binary integer: ");
int b=in.nextInt();
int answer = Integer.parseInt(in.nextInt() + "", 2);
System.out.println("The number is " + answer + ".");
}
}
2 is for base 2.

Understanding methods. Java code

Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).

Categories