I am trying to write a basic calculator. One of the things I want my calculator to have is a base arithmetic converter that gives an output when you input a base 10 integer.
I tried to write code for it on my own and it took nearly 3 hours just to figure out how to convert a number to a given base and it works good enough so far but I have one problem - when I try to convert an integer to base 2 (binary) my calculator does not work for numbers bigger than 1025.
I thought the problem was because there is a max value an integer can hold or something so I tried "BigInteger" but since it does not support remainder "%" operation I could not make it work.
else if(c.equals("Base")) {
g = 0;
l = 0;
System.out.println("Enter the number (Integer) you want to convert");
f = scan.nextInt();
System.out.println("Enter the arithmetic base you want for your new number");
m = scan.nextInt();
for (;f>=1;) {
h=f%m;
f=f/m;
k = (int)Math.pow(10,g);
g++;
l =l + (h*k);
}
System.out.println(l);
}
Sorry if the code is really bad and there are more efficent ways, i just wanted it to be mine instead of looking it up.
If you want to use the BigInteger class, you can use the mod method instead of "%".
BigInteger myBigInteger = new BigInteger("943838859");
System.out.println(myBigInteger.mod(BigInteger.TEN));
This will print 9.
It's not a good idea to store the "binary representation" in an int variable, since that limits you to 10 digits.
Instead, you can use a String variable to hold the result:
String l = "";
while (f > 0) {
h = f % m;
f = f / m;
l = h + l;
}
System.out.println(l);
This is the way I've tried myself (modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001
You can do this in a 3 lines of code using a recursive funtion,
public static String convertToBase(int n, int b) {
return n > 0 ? (convertToBase(n / b, b) + n % b) : "";
}
Related
I have an integer in java. How do I replace its’ first three numbers with 111(or any other number), for example turning 783729 into 111729?
Many thanks!
You could convert it into a string and then replace the first three letters.
String s = String.valueOf(783729);
int i = Integer.parseInt(s.replace(s.substring(0, 3), "111"));
Convert the integer to string replace the first three characters and convert it back to integer.kindly try to do it yourself. if you feel stuck during coding post your code along with the problem you face.
You can do this without converting to a string using simple arithmetic:
// Assumes that num is initially at least 999.
int replaceWith111(int num) {
if (num < 1000) {
return 111;
}
return 10 * replaceWith111(num / 10) + (num % 10)
}
Obviously if you just need to get this done you'd convert to String and do the substitution there.
However, just for fun, here's how you could do it using only Math functions and operators. Doesn't handle negative numbers - that's left as an exercise fo the reader :)
int s = 111;
int n = 783729;
int ds = (int)Math.ceil(Math.log10(s));
int dn = (int)Math.ceil(Math.log10(n));
int b = (int)Math.pow(10, dn-ds);
int sn = s * b + n % b;
System.out.println(sn);
Output:
111729
This is a program to check if an input is power of 2 or not. This program is running fine for inputs up to 8 digits but when I am giving input like 1018, it is not working, What should I do?
import java.util.Scanner;
public class search {
public static void main(String [] args){
//to take how many inputs are there
Scanner sc = new Scanner(System.in);
int k ;
k = sc.nextInt();
for(int i = 0 ;i<k;i++){
// input number n
long n ;
n = sc.nextInt();
if ((n > 0) && ((n & (n - 1)) == 0)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
The problem is that 1018 is out of range of Java int, which stores numbers up to 231-1, or roughly 2*109. You can expand the range of your program by using long in place of int to accept numbers up to 9*1018, or to make it accept virtually unlimited range by using BigInteger:
BigInteger n = new BigInteger(numericString);
BigInteger test = n.and(n.subtract(BigInteger.ONE));
if (test.equals(BigInteger.ZERO)) {
...
}
You need to get your input number as String then use BigInteger class to avoid limit surpassing problem,
BigInteger inputNumber = new BigInteger(inputString);
Also, refer What does BigInteger having no limit mean? to know more about BigInteger limits.
If the long number range is enough, you can just change
n = sc.nextInt();
to
n = sc.nextLong();
At the moment, n is only set to an integer and therefore limited to the int number range.
Better Use Class BigInteger it implement Serializable, Comparable<BigInteger> .BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
input="Number"
BigInteger number = new BigInteger(input);
//Do your stuff
Happy to help thanks
Take the input in long:
k = sc.nextLong();
My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}
An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for
As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.
Am trying to print the sum of digits in 2^n for n = 1 to 1000.
Here's what I've done.
public static void main(String[] args) {
int n = 1000;
for (int i = 1; i < n; i++) {
BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
int sum = 0;
while (power.intValue() > 0) {
sum += power.intValue() % 10;
power = power.divide(BigInteger.valueOf(10));
}
System.out.print(sum + " ");
}
}
It works only till about 2^30 or so and then prints the same result, 46, for the rest.
I tried a similar thing using "long long" in C and that printed 0's after a similar limit.
According to the answers, I changed
BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
to
BigInteger power = BigInteger.valueOf(2).pow(i);
and 46 changed to 0. Just like C.
Still not working...
You're using Math.pow to generate the value you should use the BigInteger functions to do so instead.
The sum should be stored in a BigInteger as well not an int.
You are doing integer arithmetic and then putting it into a biginteger. Use a biginteger's pow method instead.
Because you aren't using BigInteger.
Computing numbers using BigInteger doesn't let you magically store their sum in an int.
Similarly, passing an int to BigInteger.valueOf() doesn't magically make that int bigger.
You're calling Math.pow() with regular integers, not BigIntegers. You're calling it on integer literals.
You want this:
int i = 7; //or whatever power
BigInteger k = BigInteger.valueOf(2);
k = k.pow(i);
I am unsure about how to generate a random n digit integer in Java using the BigInteger class.
private static Random rnd = new Random();
public static String getRandomNumber(int digCount) {
StringBuilder sb = new StringBuilder(digCount);
for(int i=0; i < digCount; i++)
sb.append((char)('0' + rnd.nextInt(10)));
return sb.toString();
}
And then you can use it:
new BigInteger(getRandomNumber(10000))
According to the docs, there is a constructor to do what you want in java 6: BigInteger(int, java.util.Random)
To that, you need only add a randomly selected 5000th digit-i.e. Use the rng constructor to 4999 digits, the add the last in via a separate random process. Actually, since you want to just sample performance for large values, you could generate the bits, and tack a one bit on the big end, rather than slave to decimal notation.
The simplest way would probably to be to fill a char[] array with 5000 random digits, convert that to a string, and then call the BigInteger(String) constructor.
If any of those steps gives you problems, please give more details.
Alternatively, you could do something like this:
Random rng = new Random(); // But use one instance throughout your app
BigInteger current = BigInteger.ZERO;
for (int i = 0; i < 5000; i++) {
BigInteger nextDigit = BigInteger.valueOf(rng.nextInt(10));
current = current.multiply(BigInteger.TEN).add(nextDigit);
}
I suspect that would be rather less efficient though.
You could reduce the number of steps required by generating nine random digits at a time, with rng.nextInt(1000000000).
Here are two versions, one takes a Random as parameter (in case you want to re-use it):
public static BigInteger getRandomNumber(final int digCount){
return getRandomNumber(digCount, new Random());
}
public static BigInteger getRandomNumber(final int digCount, Random rnd){
final char[] ch = new char[digCount];
for(int i = 0; i < digCount; i++){
ch[i] =
(char) ('0' + (i == 0 ? rnd.nextInt(9) + 1 : rnd.nextInt(10)));
}
return new BigInteger(new String(ch));
}
The resulting BigInteger will always have the specified length.
If n is between 1 to 12 then following method helps
private String getRandom(int length) {
if (length < 1 && length > 12) {
throw new IllegalArgumentException("Random number generator length should be between 1 to 12");
}
long nextLong = Math.abs(random.nextLong());
return String.valueOf(nextLong).substring(0, length);
}
One more thing to note is that it is not well tested code.
Take a string with 5000 digits in it then convert it into BigInteger.