Turn Assembler algorithm to a Java Sequence calculator - java

When I enter "3" in my java code, it prints
3 will be multiplied by 3 and +1
Value is 10
Any advice as to how I should modify it, so that it calculates the sequences correctly
import javax.swing.*;
public class sequences {
/**
* #param args
*/
public static void main(String[] args) {
calculateSequences();
}//ends main
public static void calculateSequences()
{
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);
if(value == 1)
{
System.out.println("Value is equal to 1, closing down");
System.exit(0);
}
else if ((value%2)==0)
{
System.out.println(value + " will be divided by 2");
value = value/2;
System.out.println("Value is even " + value);
}
else
{
System.out.println(value + " will be multiplied by 3 and +1");
value = 3*value+1;
System.out.println("Value is " + value);
}
}//ends calculateSequences
}//ends class

You forgot the "go to start"
Here are the results from one test.
23 will be multiplied by 3 and + 1
Value is 70
70 will be divided by 2
Value is even 35
35 will be multiplied by 3 and + 1
Value is 106
106 will be divided by 2
Value is even 53
53 will be multiplied by 3 and + 1
Value is 160
160 will be divided by 2
Value is even 80
80 will be divided by 2
Value is even 40
40 will be divided by 2
Value is even 20
20 will be divided by 2
Value is even 10
10 will be divided by 2
Value is even 5
5 will be multiplied by 3 and + 1
Value is 16
16 will be divided by 2
Value is even 8
8 will be divided by 2
Value is even 4
4 will be divided by 2
Value is even 2
2 will be divided by 2
Value is even 1
Value is equal to 1, closing down
Here's your code with a while clause added.
import javax.swing.JOptionPane;
public class Sequences {
/**
* #param args
*/
public static void main(String[] args) {
calculateSequences();
}// ends main
public static void calculateSequences() {
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);
while (value > 0) {
if (value == 1) {
System.out.println("Value is equal to 1, closing down");
System.exit(0);
} else if ((value % 2) == 0) {
System.out.println(value + " will be divided by 2");
value = value / 2;
System.out.println("Value is even " + value);
} else {
System.out.println(value + " will be multiplied by 3 and + 1");
value = 3 * value + 1;
System.out.println("Value is " + value);
}
}
}// ends calculateSequences
}

You need to add iteration or recursion. Since this is Java, it would make most sense to use iteration.
This corresponds to the line "go to start ;" in the algorithm.
For this you can use a while loop, such as while(true).

public static void main(String[] args) {
process(Integer.parseInt(args[0]));
}
private static void process(int n) {
while (n != 1) {
if (n%2 == 0) {
System.out.println(n + " will be divided by 2");
n = n/2;
System.out.println("Value is even " + n);
}
else {
System.out.println(n + " will be multiplied by 3 and +1");
n = 3*n+1;
System.out.println("Value is " + n);
}
}
System.out.println("Value is equal to 1, closing down");
}
And the output:
3 will be multiplied by 3 and +1
Value is 10
10 will be divided by 2
Value is even 5
5 will be multiplied by 3 and +1
Value is 16
16 will be divided by 2
Value is even 8
8 will be divided by 2
Value is even 4
4 will be divided by 2
Value is even 2
2 will be divided by 2
Value is even 1
Value is equal to 1, closing down

Related

Exercise java recursion

I don't understand how this exercise return the number's square. In particular I don't understand the sixth line in which there is return statement and after this "+2*x-1". What is the program behavior in that call?
public class Es {
public static int RecCalc(int x) {
if (x==0) {
return 0;
}else {
return RecCalc(x - 1) + 2 * x - 1;
}
}
public static void main(String[] args) {
System.out.println(RecCalc(3));
}
}
We can see how this works with a little algebra:
(x-1)² + 2x - 1
== x² - 2x + 1 + 2x - 1
== x²
If you are unfamiliar with the formula for (x + y)² then you can do (x-1)² by writing it as (x-1)*(x-1) and using the FOIL method or the distributive property. This is left as an exercise for the reader.
Let's step through, one call at a time.
The first call to kick it all off is:
RecCalc(3);
In Java, the return statement will take everything up to the semi-colon.
So, return 3 + 2 will return 5 to the caller.
RecCalc(3) will result in calling:
RecCalc(2) + 2*3 -1;
RecCalc(2) will result in calling:
RecCalc(1) + 2*2 -1;
RecCalc(1) will result in calling:
RecCalc(0) + 2*1 - 1;
RecCalc(0) will return 0.
Now we can work our way back up the call stack.
RecCalc(0) == 0
RecCalc(1) == RecCalc(0) + 2*1 -1 == (0) + 2*1 -1 == 1
RecCalc(2) == RecCalc(1) + 2*2 -1 == (1) + 2*2 -1 == 4
RecCalc(3) == RecCalc(2) + 2*3 -1 == (4) + 2*3 -1 == 9
This doesn't explain the math, but explains the recursion.
Let's look at the math.
As explained by #CodeApprentice, x² = (x-1)² + 2x -1
The real trick to this whole recursive scheme is the (x-1)².
We know that for x = 4, we can use (x-1)² plus some other junk to get the answer.
But that's just the square of 3 plus some other junk!
Now, to get the square of 3, we know that 3² = (x-1)² plus junk.
But that's just the square of 2 plus some other junk!
And so, we work our way down until we get to a trivial answer, where we return 0. (In fact, you could also return 1 for x=1).
I hope that explains it!
If you have 4 things, you can make a square with side 2:
xx
xx
If you want to make a square with side 3, you need 9 things: add 2 things on each of the side and bottom, plus 1 for the corner:
xx.
xx.
..+
Or, to put it another way, add 3 things on each of the side and bottom, take away 1 for the corner.
Generalizing, if you have a square of side length (n-1), to make a square of side length (n), you have to add on 2 lots of (n-1) things, plus one; or 2 lots of (n) things, take away one.
Hence:
number of things in a square of side length n
= (number of things in a square of side length (n-1))
+ 2 * (n-1) + 1
= (number of things in a square of side length (n-1))
+ 2 * n - 1
Perhaps if you put in a print statement it will help.
public static void main(String[] args) {
System.out.println(RecCalc(5));
}
public static int RecCalc(int x) {
if (x == 0) {
return 0;
} else {
int v = RecCalc(x - 1) + 2 * x - 1;
System.out.println((x-1) + " " + (2*x) + " " + (-1));
return v;
}
}
Prints
0 2 -1
1 4 -1
2 6 -1
3 8 -1
4 10 -1
25
Notice that the value of the sum of the last two columns in each line is an odd number. And the sum of any number of consecutive odd numbers starting with 1 is a perfect square. So essentially, this method just sums up the first x odd numbers.

Why is my test case failing for the hailstones method?

Returns a string consisting of a Hailstone sequence beginning with the positive integer n and ending with 1. The
string should consist of a sequence of numerals, with each numeral followed by a single space. When a numeral m
(other than 1) appears in the sequence, it should be followed by nextHailstone(m).
Examples: nextHailstone(1) is "1 " and nextHailstone(5) is "5 16 8 4 2 1 ".
public static String hailstones (int n)
{
int calculation = 1;
System.out.print(n + " ");
while (n > 1)
{
if (n % 2 == 0)
{
n /= 2;
}
else
{
n = (n*3) + 1;
}
calculation++;
System.out.print(n + " ");
}
return " ";
}
The code works fine when I call the method in the main method but the test case for it is failing.
#Test
public void testHailstones ()
{
assertEquals("1 ", hailstones(1));
assertEquals("16 8 4 2 1 ", hailstones(16));
assertEquals("7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ", hailstones(7));
}
Those are the test cases. any insight into this would be great. thanks!
You return " " every time the function is called. You need to build up an internal string and return that as result.

Convert given number to power in Java

I have a main function that calls another function and passes the given number as a parameter. In the other function, I want to break up the given number into sums of power. How can this be done?
My code looks like:
public static void main()
{
String hello=raisetopower(in.nextInt());
}
public String raisetopower(int n)
{
// do the logic
}
Explanation :
say if the number is 25: the function should return 5^2 + 0^2
and if it is 26: 5^2+1^2
I agree with Richard's comment that this more Mathematics than Java
The question needs more information to be able to provide code to assist, such as whether or not you consider a maximum base like 10 and whether or not all bases should be in the output even if they are to the power of 0 as your example is confusing:
"say if the number is 25: the function should return 5^2 + 0^2 and if
it is 26: 5^2+1^2"
However with that in mind, hopefully this example will be able to assist
Assuming you do have a maximum base being considered, you could start from the highest base to the lowest and use logs
If the result of the log is greater than or equal to 1, then this value should be in the output, so subtract that value and continue on to the next base
Keep continuing until you hit a value of exactly 1 and that should be your end condition
E.g assuming a maximum base of 5 for this example with an input of 27
log5 27 = 2.04781858346
so we will have 5^2 in the output and subtract this from the input, you could use floor to extract the '2'
log4 2 = 0.5
less than one so not an integer power
log3 2 = 0.630929753571
less than one so not an integer power
log2 2 = 1
add to output as greater than or equal to 1 and terminate as it is exactly 1
If you're only displaying bases with powers greater than or equal to one (this was unclear), your output at this point would be:
27 = 25^2 + 2^1
You could use a StringBuilder or an ordered collection of custom objects holding your bases and powers to make it easier to generate the output
Here's an SSCCE for my above algorithm:
import java.util.Scanner;
public class NumberToPowerConversion {
public static void main(String[] args) {
int maxBaseToConsider = 5;
System.out.println("Input number to convert: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
StringBuilder output = new StringBuilder("Represented as powers: " + number + " = ");
for(int base = maxBaseToConsider; base >= 1; base--){
//Prevent division by 0 (log 1)
double logResult = base > 1 ? Math.log(number) / Math.log(base) : 1;
int floorResult = (int)Math.floor(logResult);
if(number == 1 || logResult == 1.0){
output.append(base + "^" + floorResult);
number -= Math.pow(base, floorResult);
if(number != 0){
//If the number couldn't be broken down completely, add the remainder to the output
output.append(" + " + number + "^1"); //To keep format consistent
}
break; //end condition reached
}
else if(floorResult >= 1){
output.append(base + "^" + floorResult);
number -= Math.pow(base, floorResult);
if(number == 0){ break; }
else{ output.append(" + "); }
}
}
System.out.println(output.toString());
}
}
Example output:
Represented as powers: 27 = 5^2 + 2^1
Represented as powers: 77 = 5^2 + 4^2 + 3^3 + 2^3 + 1^1
Represented as powers: 234 = 5^3 + 4^3 + 3^3 + 2^4 + 1^1 + 1^1
Represented as powers: 99 = 5^2 + 4^3 + 3^2 + 2^0
Represented as powers: 1 = 5^0
I have actually found the solution of this problem over here : https://github.com/Widea/Interview-Questions/blob/master/Hard/Random/PowerNumbers.java
/* Algorithm :
i <- square root of n
while n<1
n <- n-square of i
r <- r concatenate with i^2
if n=0 r concatenate with i^0
if n=1 r concatenate with i^1
i <- square root of n
return r
*/
public static String raisetopower(int n){
String raised="";
int i=(int)Math.sqrt(n);
while(n>1){
n=n-(int)Math.pow(i,2);
raised+=String.valueOf(i)+"^2+";
if(n==0)
raised+="0^2";
if(n==1)
raised+="1^2";
i=(int)Math.sqrt(n);
}
return raised;
}

Recursion - explanation how the code works (drawing)

i write this code and i try to understand all activities performed (recursive).
Can anyone help me with this draw me up a tree in memory of what happens?
public static String row(int n) {
if (n == 1)
return "1";
else
return row(n - 1) + " " + n;
}
public static String triangle(int a, int b) {
if (a == b)
return row(b);
else
return row(a) + "\n" + triangle(a + 1, b);
}
}
thank's
Your row method:
public static String row(int n) {
if (n == 1) {
return "1";
} else {
return row(n - 1) + " " + n;
}
}
Returns a String containing all the numbers from 1 - n separated by spaces. E.g.row(4) will return a string "1 2 3 4".
Your triangle method prints one row for each row of a triangle.
public static String triangle(int a, int b) {
if (a == b) {
return row(b);
} else {
return row(a) + "\n" + triangle(a + 1, b);
}
}
creates one row of a triangle for each step of row from a up to b.
e.g. triangle(4,6) will print:
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
How the code works
The row method, if given the value 1 will return "1". Any other value will result in a string equivalent to row(n-1) followed by n so essentially it will return 1 2 3 ... n.
The triangle method returns a string which attempts to draw a triangle with numbers. Thus triangle(4,6) returns row(4) + triangle(5,6) which returns row(5) + triangle(6,6) which will returns row(6). Thus the final result will be:
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6

Java recursion sum of number non divisible by specific number

I have to find sum of the all even numbers that are not divisible by 7 using recursion. I tried this code but it seems I am making mistake somewhere because it returns 0:
public static void main(String[] args) {
System.out.println(specialSum(50));
}
public static int specialSum(int a) {
if ((a >= 1) && ((specialSum(a-1))%7 !=0)) {
return a + specialSum(a -1);
} else{
return 0;
}
}
}
Instead of if ((a >= 1) && ((specialSum(a-1))%7 !=0)) try if ((a >= 1) && (a%7) !=0)), as it is now, you're never checking if the original a value is not divisible by 7, your first check is always a - 1.
In recursion, you just need to focus on current step, you shouldn't user specialSum(a -1) in a condition. This is the next step, you should only call it after focusing on the current step.
You should just apply your two rules to succeed : add the current number to the nexts only
- if they are even
- if they are not divisible by 7.
public static int specialSum(int a) {
if(a <= 1) // Final Case.
{
System.out.print(" 0 = ");
return 0;
}
if(a%2 != 0) // Even Number, do not sum, call next step
{
return specialSum(a-1);
}
else
{
if(a % 7 == 0){ // Divisible by 7 Do not sum, call next step.
return specialSum(a-1);
}
else // NOT divisible by 7 nor by 2, add it to the next step
{
System.out.print(a+ " + ");
return a + specialSum(a-1);
}
}
}
outputs :
50 + 48 + 46 + 44 + 40 + 38 + 36 + 34 + 32 + 30 + 26 + 24 + 22 + 20 + 18 + 16 + 12 + 10 + 8 + 6 + 4 + 2 + 0 = 566
Here you have the solution in one line, you should have a case to stop the recursion, in your case you stop the recursion at 49 because it is divisible by 7, and you don't take into account numbers less than 49
main()
{
specialSum(50, 7);
}
public static int specialSum(int a, int toDivide)
{
return (a == 0) ? 0 : (a >= 1 && a%2 == 0 && a%7 != 0) ? a + specialSum(a - 1, toDivide) : specialSum(a - 1, toDivide);
}
This works for me. The first if makes sure to only take even numbers. Then second if makes sure only to sum if not divisible by 7. The last if sums the result.
public static void main(String[] args) {
System.out.println(specialSum(50, 0));
}
public static int specialSum(int max, int current){
if(max % 2 == 1)
max -= 1;
if(max % 7 != 0)
current += max;
if(max >= 1){
max -= 2;
return specialSum(max, current);
}
return current;
}
This returns 566.
Equal to: 50 + 48 + 46 + 44 + 40 + 38 + 36 + 34 + 32 + 30 + 26 + 24 + 22 + 20 + 18 + 16 + 12 + 10 + 8 + 6 + 4 + 2.
public static int specialSum(int a) {
if ( a % 7 !=0 && a%2==0 ) {
return a + specialSum(a - 2);
} else {
if (a > 2 ) {
a=a-2;
return a + specialSum(a - 2);
} else {
return 0;
}
}
}
Your code is wrong.
The condition (specialSum(a-1))%7 !=0) in your code calls the method for 49, when a=50. This calls the method for 48, which calls for 47 and so on until a=1. Then, it calls for 0, which is not greater than or equal to 1, and hence it returns 0. Now, 0%n for any number, is 0. Hence, you get 0 as the output.
Change your method to something like this:
public static int specialSum(int a) {
if(a<=2) return 2; // base case
else if(a%7==0) return specialSum(a-2); // if it is divisible by 7, then do not add it, and call the method for a-2.
else return a+specialSum(a-2); // else add the number, and get the answer for a-2.
}
You need to check if a is divisible by 7, so you should use if ((a>=1) && (a%7) !=0)) to make sure that the you check for the base condition.

Categories

Resources