What exactly does this log10(int) method in Java? - java

I'm checking a Java code from an online test and I try to understand what exactly is this log10() method.
This is an image with the code from the test:
I added the code in my Eclipse and I get some errors:
public class Demo {
public static String numbers(int from, int to) {
int maxDigits = ceil(log10(to));
int len = (to - from + 1) * (maxDigits + 1);
char[] chars = new char[len];
len = 0;
for (int index = from; index < to; index++) {
char[] reversed = new char[maxDigits];
int wip = index;
int digit = 0;
while (wip > 0) {
reversed[digit++] = (char) ('0' + wip % 10);
wip = 10;
}
while (digit-- > 0) {
chars[len++] = reversed[digit];
}
chars[len++] = ' ';
}
return new String(chars, len);
}
public static void main(String[] args) {
Demo.numbers(11, 15);
}
}
Can somebody help me to understand what does this ceil(log10(to)) statement? Because I get a compilation error at this line: "The method log10(int) is undefined for the type Demo". Anyway I think this code has some error because also I have another compilation error at the end "The constructor String(char[], int) is undefined".
I've did a Java test online and I have no idea what is the output. And now I want to check it to learn from it. Any feedback will be apreciated! Thank you!

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log10(double)
Returns the base 10 logarithm of a double value.
Google search was "java math log10" and I then picked the first official API documentation, which was the third result.

The code is simply missing imports.
import static java.lang.Math.log10;
public class MyClass {
public static void main(String[] args) {
System.out.println(log10(100));
}
}
Output:
2.0
log10 is just the logarithm with base 10, see here.

To answer the question in your header, please consider these examples.
log10 11 = 1.04139269
log10 101 = 2.00432137
log10 1001 = 3.00043408
log10 10001 = 4.00004343
log10 99999 = 4.99999566
log10 tells you how many digits (in base 10) the number has (minus 1). So all the five digit numbers, from 10000 to 99999, have a log10 that is greater than or equal to 4.0 but less than 5.0. If you take the ceil of the log10, you'll get 5.
Put another way, if x is any 5-digit number, then int(ceil(log10 x)) = 5.

Related

When i try to calculate 2 power n when n above 30 i get 0, how can i fix it?

for my home work i need to write code to calculate 2 power n (2^n)
while i managed to make it work for n from 0 to 30, for 31 i get -2147483648
and for any n above 31 (33,35,40..) i just get 0.. how can i take care of it?
i need to use simple commands i cant use math pow
public class Task3a {
public static void main(String[] args) {
//---------------write your code BELOW this line only!--------------
Scanner myScanner = new Scanner (System.in);
int n = myScanner.nextInt();
int expo = n ;
int base = 2;
if (n==0){
System.out.println("1");
}
if (n==1){
System.out.println(base);
}
else{
while(expo>1){
base = base * 2 ;
expo = expo - 1;
}
System.out.println(base);
}
//---------------write your code ABOVE this line only!--------------
}
}
as i said , for an example for 2^35 i get 0
You need to switch to use the primitive long. The primitive int has a limited value of 2^(+/-)31 so it is defaulting to zero once it has that limit.
Use BigInteger . So 2^35 is:
BigInteger base = new BigInteger("2");
int power = 35;
BigInteger answer = base.pow(power);
System.out.println(answer.toString());

Find Cube Root of Number (without using cbrt()) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code works perfectly for some floating value such as 125.5:
public class NewClass {
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
NewClass ob = new NewClass();
double n = Input.nextDouble();
double cbrt = ob.Cbrt(n);
System.out.println(cbrt);
}
public double GetSquareRoot(double n, double low, double high) {
double cbrt = (low + high) / 2;
if (cbrt*cbrt*cbrt > n)
return GetSquareRoot(n, low, cbrt);
if (cbrt*cbrt*cbrt < n)
return GetSquareRoot(n, cbrt, high);
return cbrt;
}
public double Cbrt(double n) {
NewClass ob = new NewClass();
return ob.GetSquareRoot(n, 0, n);
}
}
It does not give correct answer when input is:
0.008
or 0.125
or 50
or 100
Then I am getting java.lang.StackOverflowError.
When input is 125.5 or 125 or 8 it gives the correct solution.
Can someone help me?
The error is that this line:
return ob.GetSquareRoot(n, 0, n);
(which is, of course, misnamed) tries to find a solution between 0 and n. However, if 0 < n < 1, then n1/3 > n, so you will never find a solution in the interval (0, n). You'll need to make a special case of this; for example, if 0 < n < 1, you can search the interval (n, 1) instead.
Also, using 0 and n as the bounds won't work for negative numbers, so if you want to make your method more complete and handle those cases, you'll need special cases for those too (probably different for -1 < n < 0 and n < -1).
MORE: After seeing your comment about StackOverflowError, it's occurred to me that you have an additional problem: that you're expecting an exact result. When you put in 0.008, the cube root is 0.2. However, neither 0.008 nor 0.2 can be represented exactly as a floating-point number. The consequence is that if you let cbrt = whatever value is closest to 0.2 that can be represented, then cbrt*cbrt*cbrt won't be exactly 0.008. It can't be exactly 0.008 anyway, since 0.008 can't be represented as a double; however, if n is whatever value is closest to 0.008, then it's likely that cbrt*cbrt*cbrt will not be exactly equal to n, due to roundoff errors. For a calculation like this, it's important that you not compare doubles for equality; instead, compare them using an "epsilon" value, or a margin of error. Thus, after
double cbrt = (low + high) / 2;
you should have something like
if (Math.abs(cbrt*cbrt*cbrt - n) < EPSILON)
return cbrt;
where EPSILON is some small value such as 1E-10. (I've sometimes seen code where EPSILON is computed to be a relative value, i.e. abs(n * RELATIVE_EPSILON), instead of an absolute value.)
Another way to avoid StackOverflowError is to quit when low and high become really close, because by that point you're not going to gain much more accuracy, and you need to make sure you exit the algorithm even if the value of cbrt*cbrt*cbrt is a little bit off. Something like
if (high - low < EPSILON)
return cbrt;
See also What's wrong with using == to compare floats in Java?.
//How about My Solution - Without Recursive
import java.util.Scanner;
public class CubeRoot {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.next();
Boolean negative = false;
if (str.startsWith("-")) {
str = str.substring(1);
negative = true;
}
if (str.indexOf(".") > 0) {
// find the poisition of '.'
int pPos = str.length() - 1 - str.indexOf(".");
String plainStr = (str.substring(0, str.indexOf('.')).concat(str.substring(str.indexOf('.') + 1)));
StringBuffer cStr = new StringBuffer(cubeRoot(plainStr));
if (cStr.toString().equalsIgnoreCase(plainStr))
System.out.println("couldn't compute Cube Root for this :(");
else {
if (cStr.length() > pPos / 3) // devide 3 times to put the '.'
cStr.insert(cStr.length() - pPos / 3, ".");
else {
int cStrLength = cStr.length();
for (int i = 0; i <= pPos / 3 - cStrLength; i++)
cStr = new StringBuffer("0").append(cStr.toString());
cStr.insert(cStr.length() - pPos / 3, ".");
}
String append = (negative) ? new String("-") : new String("");
System.out.println(append + cStr.toString());
}
} else {
System.out.println("Not a floating num");
}
}
private static String cubeRoot(String d) {
Long l = new Long(d);
for (int i = 0; i < l; i++) {
if (i * i * i == l) {
return String.valueOf(i);
}
}
return d;
}
}

Java - Recursion Program - way to convert an inputted base to base 10 on a given number

I am given a non-recursive method, that I need to modify to make recursive.
This is what I have so far:
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
BigInteger answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
static BigInteger basen(int number, int base ) {
List<Integer> remainder = new ArrayList<>();
int count = 0;
String result = "";
while( number != 0 ) {
remainder.add( count, number % base != 0 ? number % base : 0 );
number /= base;
try {
result += remainder.get( count );
} catch( NumberFormatException e ) {
e.printStackTrace();
}
}
return new BigInteger( new StringBuffer( result ).reverse().toString() );
}
}
It's converting it to base 10 then the given base. I need it to convert to the given base first then base 10.
UPDATE:
I changed around Caetano's code a bit and think I am closer.
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int resultC;
String resultD;
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
if (newNumber == 0)
resultC = Integer.parseInt(result);
resultD = Integer.toString(resultC);
return resultD;
Now when I compile it it gives me an error it says:
BaseN.java:49: error: variable resultC might not have been initialized
resultD = Integer.toString(resultC);
Am I on the right track here? Any help is appreciated
Its hard to tell what you are asking for.
I can only assume that you want to convert from a given base to base 10. The way that you would do this is explained in this page here: MathBits introduction to base 10.
The way explained in this is simple. For each digit in the number you get the base to the power of the position of the digit(reversed) and multiply that by whatever the digit is. Then add all the results. So 237 in base 8 would be
(8^2 * 2) + (8^1 * 3) + (8^0 * 7) = 159
Now you will run in to a problem when you do this with bases higher then 10 since the general notation for digits above 9 is alphabetical letters. However you could get around this by having a list of values such as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F] and compare the digits with this list and get the index of the location of that digit as the number.
I hope this is what you were asking for.
Now then this is code that does what you want it to do. Get a number in a given base and convert it to base 10. However I don't see why you need to use a recursive method for this. If this is some kind of school task or project then please tell us the details because I don't personally see a reason to use recursion. However the fact that your question asks us to modify the code up top to make it recursive then it makes much more sense. Since that code can be edited to be as such.
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
String number = input.next();
int base = input.nextInt();
int answer = basen(number, base);
System.out.println(number + " base-" + base + " = " + answer);
}
private static int basen(String number, int base ) {
int result = 0;
for(int i = 0; i < number.length(); i++) {
int num = Integer.parseInt(number.substring(i, i + 1));
result += Math.pow(base, number.length() - i - 1) * num;
}
return result;
}
However what I think that you want is actually this which shows recursion but instead of converting from base given to base 10 it converts from base 10 to base given. Which is exactly what the code you showed does but uses recursion. Which means '512 6' will output '2212'
public static final int BASEN_ERRNO = -1;
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
System.out.print("enter number followed by base (e.g. 237 8): ");
int number = input.nextInt();
int base = input.nextInt();
String answer = new StringBuffer(basen(number, base)).reverse().toString();
System.out.println(number + " base-" + base + " = " + answer);
}
static String basen(int number, int base) {
String result = String.valueOf(number % base);
int newNumber = number / base;
if (newNumber != 0)
result += basen(newNumber, base);
return result;
}
I figured out a way to do it recursively. Thank you everyone who provided help. I ended up using Math.pow on the base and put the length of the number -1 for how it would be exponentially increased. Math.pow puts the result in double format so I just converted it back to an int. My professor gave me 100% for this answer, so I'd imagine it would work for others too.
public static int basen(int number, int base) {
String numberStr;
int numberL;
char one;
String remainder;
int oneInt;
int remainderInt;
double power;
int powerInt;
numberStr = Integer.toString(number);
numberL = numberStr.length();
if(numberL > 1){
one = numberStr.charAt(0);
remainder = numberStr.substring(1);
oneInt = Character.getNumericValue(one);
remainderInt = Integer.parseInt(remainder);
power = Math.pow(base, (numberL - 1));
powerInt = (int)power;
return ((oneInt * powerInt) + (basen(remainderInt, base)));
}
else{
return number;
}
}

Converting From Decimal to Binary In Java

So I have code that will convert a decimal number to binary. I use a recursive algorithm for it, however I cannot seem to get it to do what I want. Here is the code:
import java.util.*;
public class binaryAddition {
public static int toBinary(int a){
int bin = 0;
int remainder = 0;
if(a >= 1){
toBinary(a/2);
bin = (a%2);
}
return bin;
}
public static void main(String[] args){
System.out.println(toBinary(3));
System.out.print(toBinary(3));
}
}
So I want to to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I used the number 3 just as a test case and I get 1 as an output for both print and println methods. Why is that, and how can I fix it?
Many Thanks!
For a start, you might want to have toBinary return a String, not an int. Then you must use the result of it when you recurse. So you might write, inside your if,
bin = toBinary(a / 2) + (a % 2);
assuming, of course, that toBinary returns String.
If you don't do this, then you're just throwing away the result of your calculation.
The code is discarding the results of the recursive calls.
Do something with the result of toBinary in the method.
Just Do it Like i have Done .
public static void main(String[] args)
{
int n, count = 0, a;
String x = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter any decimal number:");
n = s.nextInt();
while(n > 0)
{
a = n % 2;
if(a == 1)
{
count++;
}
x = x + "" + a;
n = n / 2;
}
System.out.println("Binary number:"+x);
System.out.println("No. of 1s:"+count);
}

UVA 10023 SquareRoot Issue

I'm stuck with this problem of the UVA as I can't figure out why my solution is not good.
As long as I understand, the question is to get the integer square root of any given number from 1 to 10^1000. So my intention was to flip the bits of a BigInteger from position i/2, where i is the number of bits in the minimal two's-complement representation of the input and decrease the i value each time the square of my guess is still less than the input.
Notice that every input I've tried so far is getting the expected result!
The example for, lets say, sqrt(36) would be:
36 -> 100100
bitCount = 2 ( (6 - 1)/2 = 2)
guess = 100 (4)
(4 * 4 = 16 < 36) -> bitCount = 1;
guess = 110 (6)
(6 * 6 = 36 = 36) -> break;
So the solution to sqrt(36) is 6, awesome... This way the solution to sqrt(37), sqrt(38), sqrt(39), until sqrt(49) would be 6 too.
Maybe the code is more explanatory.
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
BigInteger bi;
for(int i = n; i != 0; i--){
bi = new BigInteger(in.next());
System.out.println(squareRoot(bi));
}
in.close();
}
private static BigInteger squareRoot(BigInteger N) {
int bitCount = (N.bitLength() - 1)/2;
int aux = 0;
BigInteger guess = BigInteger.ZERO;
while(bitCount >= 0){
guess = guess.flipBit(bitCount);
aux = guess.multiply(guess).compareTo(N);
if(aux < 0)
bitCount--;
else if(aux != 0){
guess = guess.flipBit(bitCount);
bitCount--;
}
else{
break;
}
}
return guess;
}
}
For sure it is not the best performance solution and it seems to be wrong, but could someone explain me the reason why it is wrong?
Thank you guys!
From the problem statement:
The Output
For each test case, your program should print X in the same format as Y was given in input.
Print a blank line between the outputs for two consecutive test cases.
I got an accepted submission by modifying your program to take this into account.
However, I would suggest binary search as a simpler approach (but the problem doesn't seem relly well defined since the number of test cases is not given, I think).

Categories