print the decimal equivalent of a binary number in java - 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.

Related

Method works but throws errors for particular numbers

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

Binary Converter Java

I am trying to make a converter that converts decimal into binary, there is a catch tho, I can't use any other loops or statements except
while (){}
And I can't figure out how to start subtracting the number that fits into the decimal when it can and not using any if statements. Does anyone have any suggestions?
import java.util.Scanner;
public class Converter{
static Scanner input = new Scanner (System.in);
public static void main (String[] args){
System.out.println ("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int sqr = 1024;
int rem;
while (dec != 0){
rem = dec / sqr;
sqr = sqr / 2;
System.out.print(rem);
}
}
}
Try this:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
System.out.println("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int div = 128;
while (div > 0) {
System.out.print(dec / div);
dec = dec % div;
div >>= 1; // equivalent to div /= 2
}
System.out.println();
}
}
Now, let's go through the code and try to understand what's going on. I'm assuming that the maximum size is 8 bits, so the variable div is set to 2n-1 where n = 1. If you need 16 bits, div would be 32768.
The programme starts from that value and attempts to do an integer division of the given number by the divider. And the nice thing about it is that it will yield 1 if the number is greater than or equal to the divider, and 0 otherwise.
So, if the number we're trying to convert is 42, then dividing it by 128 yields 0, so we know that the first digit of our binary number is 0.
After that, we set the number to be the remainder of the integer division, and we divide the divider by two. I'm doing this with a bit shift right (div >>= 1), but you could also use a divider-assignment (div /= 2).
By now, the divider is 64, and the number is still 42. If we do the operation again, we again get 0.
At the third iteration, we divide 42 by 32, and this yields 1. So our binary digits so far are 001. We set the number to be the remainder of the division, which is 10.
Continuing this, we end up with the binary number 00101010. The loop ends when the divider div is zero and there's nothing left to divide.
Try to understand, step by step, how the programme works. It's simple, but it can be very difficult to come up with a simple solution. In this case, it's applied mathematics, and knowing how integer maths work in Java. That comes with experience, which you'll get in due time.
Your code has some Problem. It is more easier to convert a decimal to binary. fro example:
int num = 5;
StringBuilder bin = new StringBuilder();
while (num > 0) {
bin.append(num % 2);
num /= 2;
}
System.out.println(bin.reverse());
I use StringBuilder to reverse my String and I prefer String because length of binary can be anything. if you use int or long, maybe overflow happen.
Update
if you you want to use primitive types only, you can do something like this but overflow may happen:
long reversedBin = 0, Bin = 0;
while (n > 0) {
reversedBin = reversedBin * 10 + (n % 2);
n /= 2;
}
while (reversedBin > 0) {
Bin = Bin * 10 + (reversedBin % 10);
reversedBin /= 10;
}
System.out.println(Bin);
Remember the algorithm to convert from decimal to binary.
Let n be a number in decimal representation:
digit_list = new empty stack
while n>0 do
digit = n%2
push digit in stack
n = n/2
end while
binary = new empty string
while digit_list is not empty do
character = pop from stack
append character to binary
end while
Java provides a generic class Stack that you can use as a data structure. You could also use lists, but remember to take the digits in the inverse order you have calculated them.
find the base 2 log of the number and floor it to find the number of bits needed. then integer divide by that bits place in 2's power and subtract that from the original number repeat until 0. doesn't work for negative. there are better solutions but this one is mine
int bits = (int) Math.floor(Math.log((double) dec) / Math.log((double) 2));
System.out.println("BITS:" + bits);
while (dec > 0) {
int twoPow = (int) Math.pow((double) 2, (double) bits);
rem = dec / twoPow;
dec = dec - rem * twoPow;
bits--;
System.out.print(rem);
}

find Factorial of no. It is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers

This is my code for factorial program. it is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers.
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
resultant = resultant * i;
}
System.out.println("Factorial of number : " + resultant);
}
You should know the size of int is fixed to 32 bits. When ever your computation results in producing a large number that cannot fit into those 32 bits, some bits will get overflowed producing a wrong result. You can try with this code.
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
int test=resultant;
resultant = resultant * i;
if(resultant<test){
system.out.println("Looks like overflow occured");
}
}
System.out.println("Factorial of number : " + resultant);
}
Better way will be to use BigInteger instead of int.
Every even number that is part of the product contributes a trailing zero to the factorial. Actually to be more precise, the trailing zero count of a (unlimited precision) product is the sum of the trailing zero counts of the inputs. In finite precision the number of trailing zeroes is obviously limited by the size of the number.
So eventually, and this happens pretty quickly, the number of trailing zeroes becomes greater than or equal to 32, in which case all bits of an int would be zero. The same thing of course happens with long, a little later, at 64 trailing zeroes. And some time before that, even though the result is not totally zero yet, it would already have stopped matching what the result would have been in unlimited precision.
For example 34! in hexadecimal is
de1bc4d19efcac82445da75b00000000
The 8 least significant digits would be what you would get if you computed it with 32 bit integers, and all those digits are zero.
Factorial of such large numbers will be very large. You have to use a data type that can store very large numbers (we are talking about billions and trillions). BigInteger data type may work. Give it a try.

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.

Calculating nth root of a positive integer in Java

My task is to write a program which prompts the user to enter a positive double a and an integer
n greater than 2, and print the value of the nth root of positive integer a to the screen with accuracy to 100 places. I've used Math.pow to be able to get the root, and I feel as though I've done everything right. The only problem is that every time I run my program, the output is 1.0, no matter what numbers I input for a and n. What is the problem with my code?
import java.util.Scanner;
import java.lang.Math;
public class Q8 {
public static void main(String[] args) {
System.out.println("Enter a positive number: ");
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
System.out.println("Enter an integer greater than 2: ");
Scanner in2 = new Scanner(System.in);
int n = in.nextInt();
System.out.println(pow (a,n));
}
private static double pow(double a, int n) {
if (n == 0){
return 1;
}
else{
double sum = Math.pow(a,(1/n));
return sum;
}
Why is the answer always 1.0?
Replace 1/n with 1.0/n.
You're getting integer division, so no matter what n is, if it's 2 or higher, then 1/n is coming out zero. Then you're raising your number to the zeroeth power, which gives 1.
Replacing 1 with 1.0 makes the division into a floating point division - that is, the result won't be truncated to an integer. This is what you want.
First of all, I'm assuming that
double sum = Math.pow(a,(1/root));
should be
double sum = Math.pow(a,(1/n));
since there is no root variable in your code.
Second of all, 1/n would give you 0 for every integer n > 1. Therefore sum would be 1.0.
You should replace it with :
double sum = Math.pow(a,(1.0/n));
or
double sum = Math.pow(a,(1/(double)n));
In order to get a division of double variables.

Categories