can't find the solution - java

public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int d = 10;
int l = 1;
for (int j=1;j<=8;j++){
int r = (binary/d%10)*l;
int k = r;
int z = r + k;
d*=10;
l*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ z +" in decimal."); // z here is out of scope of for
}
}
I need to finish this assignment using only the for loop, but I can't find a working code... This is the best i did.

Here is a pretty simple algorithm using the 2^x logic.
What it is basically doing is :
If we encounter 1 in the binary variable, we add 2^(Position of the 1) to the decimal variable
class MyClass{
public static void main(String[] args) {
int bin = 101;
String binary = String.valueOf(bin);
int decimal = 0;
for (int i = 0 ; i < binary.length() ; i++){
if (binary.charAt(i) == '1'){
decimal += Math.pow(2, binary.length() - i - 1);
}
}
System.out.println(decimal);
}
}

public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int powerOfTen = 10;
int powerOfTwo = 1;
int Decimal = 0;
for (int j=1;j<=8;j++){
int splitAnswer = (binary/powerOfTen%10)*powerOfTwo;
int old = splitAnswer;
Decimal = splitAnswer + old;
powerOfTen*=10;
powerOfTwo*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ Decimal +" in decimal.");
}
}

Related

How to calculate big numbers in java?

ex
I want the sum form 1^1 to n^n : 1^1 + 2^2 + 3^3 + .............+n^n
and I know how, but the problem that I want only the last ten numbers of the sum but I have only to use primitive data. how can I calculate large numbers using only primitive data.
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
short n = in.nextShort();
if(n < 0) {
System.out.println("please give a positive number");
return;
}
long l = rechnung(n);
System.out.println(l);
String str = Objects.toString(l, null);
String s = ziffer(str);
System.out.println(s);
}
public static long rechnung(short j) {
long summe = 0;
for(int i = 1; i <= j; i++) {
summe += Math.pow(i,i);
}
return summe;
}
public static String ziffer(String s) {
String str = "";
int k =s.length() - 10;
int cond = k + 9;
if(s.length() <= 10) {
return s;
}
for(int j = k; j <= cond; j++) {
str = str + s.charAt(j);
}
return str;
}
As you only need to keep the lower 10 digits you can use a % 10_000_000_000L to keep the digits you need with each calculation.

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);

How do I add power in java?

I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30

Java binary multiplication using integer arrays not working

I'm making a program that accepts two decimal numbers and convert them into binary numbers, which are stored in integer arrays. Then I need to do multiplication using the two integer arrays. The result should also be a binary integer array (I need to validate that using a for loop). Then I convert them result to decimal number.
So far, I have the following code. My logic to convert the decimal number to binary works fine and vice verse. However, the binary result is always somehow smaller than the expected result. I have spent a lot of time on this, could you help me check what is wrong?
public class BinaryMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int[] binaryNum1 = toBinary(num1);
int[] binaryNum2 = toBinary(num2);
System.out.println("Expected result: " + num1 * num2);
System.out.println("Decimal number 1: " + toDecimal(binaryNum1));
System.out.println("Decimal number 2: " + toDecimal(binaryNum2));
int[] resultBinaries = new int[100];
for (int i = 0; i < resultBinaries.length; ++i) {
resultBinaries[i] = 0;
}
for (int i = 0; binaryNum1[i] != -1; ++i) {
for (int j = 0; binaryNum2[j] != -1; ++j) {
resultBinaries[i + j] += binaryNum1[i] * binaryNum2[j] % 2;
resultBinaries[i + j] %= 2;
}
}
resultBinaries[99] = -1;
for (int i = 0; resultBinaries[i] != -1; ++i) {
if (resultBinaries[i] > 1) {
System.out.println("The result is not a binary!!");
}
}
System.out.println("Actual decimal result: " + toDecimal(resultBinaries));
}
public static int toDecimal(int[] binaryNum) {
int result = 0;
int factor = 1;
for (int i = 0; binaryNum[i] != -1; ++i) {
result += binaryNum[i] * factor;
factor *= 2;
}
return result;
}
public static int[] toBinary(int num) {
int[] binaries = new int[100];
int index = 0;
while (num > 0) {
binaries[index++] = num % 2;
num /= 2;
}
binaries[index] = -1;
return binaries;
}
}
A sample input & output: ( the binary validation loop works fine)
45 67
Expected result: 3015
Decimal number 1: 45
Decimal number 2: 67
Actual decimal result: 2871
for (int i = 0; binaryNum1[i] != -1; ++i) {
for (int j = 0; binaryNum2[j] != -1; ++j) {
resultBinaries[i + j] += binaryNum1[i] * binaryNum2[j] % 2;
resultBinaries[i + j] %= 2;
}
}
What happens when resultBinaries[i + j] increases to 2? It's reduced to 0 and then resultBinaries[i + j + 1] should be increased with 1, but this isn't happening in the code as far as I can see.

not getting what's wrong with my code

public class DigitRange {
public static void main(String[] args) {
String numberstr = args[0];
int numberint = Integer.parseInt(args[0]);
int large=0;
int small=0;
System.out.println("range of " +numberint + " = "+ Range(numberstr,numberint,large,small));
}
public static int Range (String numberstr, int numberint,int large,int small){
for(int i=1;i<=numberstr.length();i++){
int digit = numberint % 10;
numberint = numberint/10;
large = Math.max(digit, large) ;
small = Math.min(digit, small);
}
int range = large - small + 1;
return range; //giving me 9
}
}
What is wrong with my code ? I am having a problem with returning the correct value from my method Range. I am returning the value 9 when i should be returning the value 6. I believe i have a logic error there.
NEW problem:
public class DigitRange {
public static void main(String[] args) {
String numberstr = args[0];
int numberint = Integer.parseInt(args[0]);
int max=0;
int min=9;
System.out.println("range of " + numberstr + " = "+ Range(numberstr,numberint,max,min));
}
//finds and returns the range
public static int Range (String numberstr, int numberint,int max,int min){
if(numberint<0){
Math.abs(numberint);
for(int i=1;i<=numberstr.length()-1;i++){
int digit = numberint % 10;
numberint = numberint/10;
max = Math.max(digit, max) ;
min = Math.min(digit, min);
}
}
if(numberint>0){
for(int i=1;i<=numberstr.length();i++){
int digit = numberint % 10;
numberint = numberint/10;
max = Math.max(digit, max) ;
min = Math.min(digit, min) ;
}
int range = max - min + 1;
return range;
}
}
}
How can i get the max and min out of the scope of if{} ?
You are looking for the smallest and largest digit in the number passed as argument to your code and the difference + 1 is your range, right?
Probably small should be initialized to 9.

Categories