Calling a class in Android Studio - java

I have created in android studio an app that changes numbers from base 10 to base 2. I have created the algorithm below, but I have trouble calling the class and getting it to print the result.
Can anyone help me ? Thanks in advance.
This is my code,
public class baseconv {
float m = Float.parseFloat(number.getText().toString());
int n = (int) m;
int pow = 1;
int x = 0;
public void calculate () {
while (n > 0) {
x = x + (n % 2)*pow;
n = n / 2;
pow = pow * 10;
}
}
}

To convert integer in base 10 to base 2 try this,
String baseTwoString = Integer.toString(your_integer, 2);
But if you are particular that you need to use your custom algorithm read on.
In your Activity,
String input = number.getText().toString();
try {
int n = (int) Float.parseFloat(input);
BaseConvert converter = new BaseConvert();
int output = converter.calculate(n);
Log.e("output : ", output);
} catch(NumberFormatException e) {
e.printStackTrace();
}
Your converter class,
public class BaseConvert {
public int calculate (int n) {
int pow = 1;
int x = 0;
while (n > 0) {
x = x + (n % 2) * pow;
n = n / 2;
pow = pow * 10;
}
return pow;
}
}

Related

Checking whether an int is palindrome or not without converting into a string?

public class Palindrome {
public static void main(String args[]) {
int x = 121;
int res = 0;
while (x > 0) {
res = res * 10 + (x % 10);
x /= 10;
}
if (x - res == 0) {
System.out.println("True" + res);
} else
System.out.println("False" + res);
}
}
Hello! This code is to check if an integer is a palindrome without converting the int to a String. For some reason, the computer thinks res is not same as x though both represent the number 121. Appreciate your help and thanks in advance!
You were close. Here is a solution building on what you did:
static bool isPalindrome (int n1, int n2) {
return getReverseInteger(n1) == n2;
}
static int getReverseInteger (int n) {
int nReversed = 0;
while (n > 0) {
int digit = n % 10;
nReversed = nReversed * 10 + digit;
n = (n - digit) / 10;
}
return nReversed;
}

How to add power function to sigma

I've written this code that computes the sum of the positive divisors, and all the values have to be to the power of a.
For instance:
sigma(0,14) = 1^0 + 2^0 + 7^0 + 14^0 = 4;
sigma(2,12) = 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2 = 210.
sigma(a, b).
I have tried different versions but I don't know how to add the power function.
try {
int a = Integer.parseInt(input1.getText());
int b = Integer.parseInt(input2.getText());
int result1 = 0;
for (int i = 2; i <= Math.sqrt(b); i++)
{
if (b % i == 0)
{
if (i == (b / i))
result1 += i;
else
result1 += (i + b / i);
}
}
result.setText(String.valueOf(result1 + b + 1));
}
}
In Java the ^ character means XOR.
The power function is provided by the Math.pow() method.
So 3^2 would be Math.pow(3, 2).
If you wanted to implement it yourself for integers, you could do it simply like this:
double power(int a, int b) {
int pow = (b < 0) ? -b : b;
double result = 1;
for (int i = 0; i < pow; i++) {
result *= a;
}
return (b < 0) ? 1 / result : result;
}
But I wouldn't do it myself. It gets a bit more complicated for floating points, and Java has a native underlying implementation which is much faster.
IntStream delivers beautiful concise calculation.
static int sigma(int exp, int num) {
IntStream.rangeClosed(1, num) // 1, ..., num
.filter(k -> num % k == 0) // Only divisors
.map(k -> pow(k, exp))
.sum();
}
static int pow(int k, int exp) {
if (exp == 0) {
return 1;
}
int squareRoot = pow(k, exp/2);
int n = squareRoot * squareRoot;
return (exp % 2) == 0 ? n : n*k;
}
The power calculation can be optimized by not using exp# multiplications of k but square roots.
For those interested in program transformation:
pow(k, exp) needs only to rely on exp with recursion to exp/2 (integer division). So you could turn the code inside out, have a vector of divisors,
and operate on that.
If you want to implement it without using Math.pow() you can simply follow the mathematical definition of the exponentiation for a positive exponent:
public static long exp(int a, int b){ //computes a^b
long result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
I would recommend that you use Java lambdas to accomplish what you're looking for.
Taking an input and returning a List of positive divisors seems useful on its own.
Raising every entry to a power could be done easily with a lambda.
Keep the two functions separate. Take a more functional approach.
Here is a simple code for you:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
List<Integer> listOfBs = new ArrayList<>();
System.out.println("Input your a");
int a = scanner.nextInt();
System.out.println("Input your b");
int b = scanner.nextInt();
int sqrt = (int) Math.sqrt(b);
for (int i = 1; i <= sqrt; i++) {
if (b % i == 0) {
listOfBs.add(i);
int d = b / i;
if (d != i) {
listOfBs.add(d);
}
}
}
int sigma = 0;
for(int e : listOfBs)
{
sigma += Math.pow(e,a);
}
System.out.println("Your sigma function is: "+sigma);
}
}

Java Program to determine value of nested radical constant with 10^-6 precision

Nested radical constant is defined as:
I am writing a Java program to calculate the value of nested radical constant with 10^-6 precision and also print the number of iterations required to get to that precision. Here is my code:
public class nested_radical {
public nested_radical() {
int n = 1;
while ((loop(n) - loop(n - 1)) > 10e-6) {
n++;
}
System.out.println("value of given expression = " + loop(n));
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
This code does what it is supposed to but it is slow. What should I do to optimize this program? Can someone suggest another possible way to implement this program?
I also want to write a same kind of program in MATLAB. It would be great if someone could translate this program into MATLAB too.
I have made some changes in this code and now it stores the value of loop(n - 1) instead of computing it every time. Now this program seems much optimized than before.
public class nested_radical {
public nested_radical() {
int n = 1;
double x = 0, y = 0, p = 1;
while ( p > 10e-6) {
y=x; /*stored the value of loop(n - 1) instead of recomputing*/
x = loop(n);
p = x - y;
n++;
}
System.out.println("value of given expression = " + x);
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
I also successfully translated this code in MATLAB. Here is the code for MATLAB:
n = 1;
x = 0;
p = 1;
while(p > 10e-6)
y = x;
sum = 0;
m=n;
while (m > 0)
sum = sqrt(sum + m);
m = m - 1;
end
x = sum;
p = (x-y);
n = n + 1;
end
fprintf('Value of given expression: %.16f\n', x);
fprintf('Iterations required: %d\n', n);

Simplify a square root

Let's say that I want to calculate the square root of 8. There are two ways to display the result as you can see here:
I think that the best way I have to obtain the second solution is this:
I want to try do display in my Java application 2√2 instead of 2,828427... and so I thought to develop a class following these steps. Let's consider the square root of 8.
Get the prime factors of 8 (2*2*2)
Count the exponent and try to export them (2^2 * 2 --> 2√2)
I have developed, as you can see below, a code that outputs the factors. If you input 8, the method estraiRadice() will output 2 * 2 * 2, which is correct.
private int b = 2;
public String estraiRadice(double x) {
String resRad = "";
int[] exponents = new int[100];
//Scomposizione in fattori primi
while (x > 1) {
if ((x % b) == 0) {
x /= b;
resRad += String.valueOf(b) + " * ";
} else {
b++;
}
}
return resRad;
}
The second step is giving me problems because I don't know exactly how to do create the power of a number and export it from the square root. I mean: how can that √2*2*2 become a √4*2 and then 2√2?
I thought that I could store in an array the exponent for each base and then try to export it somehow. Do you have any advice?
Try this:
public static int[] squareRoot(int number) {
int number1 = number;
List<Integer> roots = new ArrayList<>();
int coefficient = 1;
for (int i = 2; i < number1; i++) {
if (number1 % (i * i) == 0) {
roots.add(i);
number1 /= i * i;
for (int j = 2; j < number1; j++) {
if (number1 % (j * j) == 0) {
roots.add(j);
number1 /= j * j;
}
}
}
}
for (int root : roots) coefficient *= root;
return new int[]{coefficient, number1};
}
You can call it like this:
System.out.println(squareRoot(96)[0] + "√" + squareRoot(96)[1]);
You can use a HashMap to store prime number power pairs
HashMap<Integer,Integer> getRoots(int x)
{
HashMap<Integer,Integer> retval = new HashMap<Integer,Integer>();
int i=2;
while(i<=x)
{
int power = 0;
while( x%i == 0)
{
power++;
x /= i;
}
if(power>0)
{
retval.put(i,power);
}
if(x==1)
{
break;
}
i++;
}
return retval;
}

how to get exponents without using the math.pow for java

This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}

Categories