Java Square function - java

Would anyone be able to explain these methods with a few comments line. They are for squaring a number. One is using recursion, implementation and another is just normal
public static int sq(int n)
{
int i = 0 ;
int result = 0 ;
while(i < n){
result = result + 2*i + 1 ;
i = i + 1 ;
}
return result ;
}
public static int recSq(int n)
{
if(n == 0){
return 0 ;
} else {
return recSq(n - 1) + 2*(n - 1) + 1 ;
}
}
public static int implementSq(int n)
{
int i ;
int result = 0 ;
for(i = 0 ; i < n ; i++){
result = result + 2*i + 1 ;
}
return result ;
}

I presume this must be a homework exercise, otherwise its an insane way to do anything. Therefore can I suggest using an integrated development environment (e. g. Netbeans) and then using it to step through the code line by line. This is by far the easiest way to understand what the code is doing. If we just tell you, you won't gain anything by it.

The first one is multiplying the number by 2 n times using a loop to increase a local variable i.
The second one is doing exactly the same but using recursion. Each step decreasing n and returning 0 for the final case. All the calls are calling again to the same function with different parameters exept for the parameter value 0, then the function will return 0. Recursion is not a simple thing to think off, to understand it better try to imagine the codeflow.
Example: recSq(2)
4 recSq(2)
|<- 1 reqSq(1)+2*1+1
|<-0 reqSq(0)+2*0 + 1
|<- 0
reqSq(2) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 2 then we call to reqSq(1).
reqSq(1) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 1 then we call to reqSq(0).
reqSq(0) is called so we will eval the if, it's true cause n ==0 and then we return 0.
reqSq(1) call has finished evaluating reqSq(0) and then we can proceed calculating the rest 0 + 2*(n-1) + 1 -> 0 + 0 + 1. We will return the value 1.
reqSq(2) has finished evaluating reqSq(1) and then we can proceed calculating the rest 1 + 2*(n-1) +1 -> 1 + 2 + 1. We will return the value 4.
The last one is a for loop, practically the same as the first one but using fors instead of while loops. In a for loop you declare in one line the initialization condition, the continue condition and the increase operation. So in that case the for loop is starting with value 0, the loop will continue as i < n and at the end of the loop "i++" will be called.

why are you trying to solve such a simple problem with recursion or loop?
public static int sq(int n) {
return n * n;
}
that's it.

Related

How to calculate the number of zeros in binary?

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

Setting numbers from 1 to chosen number using recursion only

After about 7 hours in a row I really need some help , I need to return from recursion the amount of options that can be by setting numbers from 1 to chosen number(maximum number) , it's forbidden to use loops/arrays , only recursion , the numbers are all positive(more than 0) and goes only more positively , example : good one : {1,2} , bad one : {2,1}.
example :
n = 3 , max = 2
n : The numbers that should be in the row
, max : The maximum number that can be in the row.
{1,1,1}
{1,1,2}
{1,2,2}
{2,2,2}
from that example that should return 4 because there are 4 options of 3 numbers that their value is maximum 2.
another one:
n=2
max=3
{1,1}
{1,2}
{1,3}
{2,2}
{2,3}
{3,3}
from that example it should return 6 because there are 6 options.
Without prior knowledge, this would probably be a challenging question even for an experienced mathematician. It is the count of multisets, one of the fundamental building blocks in combinatorics. I'll explain my understanding of the idea for the recurrence relation in Wikipedia.
Typically k is used for the multiset cardinality (what your question refers to as n), while n is used as the cardinality of the set (not multiset) to choose from (the max in your question).
For f(n, k), the base cases are:
f(n, 0) = 1
one way to fill the empty multiset
And,
f(0, k) = 0
no ways to choose from an empty set
For the regular case, we consider the nth element (from the set of choices). We'd like to count all the combinations that include it and all those where it's missing. Counting all combinations without the nth element is easy: we have the same multiset counting function applied to k with one less choice:
f(n - 1, k)
Now to count the combinations that include at least one nth element, we imagine taking all the ways of choosing from n items (some of which will not include an nth element) but saving one place in each combination where we will place an nth element, so we end up with:
f(n, k - 1)
Putting it all together:
function f(n, k){
if (n == 0)
return 0;
if (k == 0)
return 1;
return f(n - 1, k) + f(n, k - 1);
}
console.log(f(2, 3));
console.log(f(3, 2));
Recursion can be hard to comprehend at first, but it is very clear to read once you get to know it. The downside is that recursion requires way more space than the basic for-loop (Space complexity of recursive function). For some problems it can be easier to first write the recursive version and afterwards write it as for-loop. Also, if space is not a problem, it helps to make your code clean (no for-loops!)
I made some basic recursion that gives the correct answer for at least the two examples you wrote down. It may be possible that I missed an edge case: maybe a good practise to write every function call and some (edgy) test cases.
public int recursiveWrapper(int n, int max) {
return recursive(n, max, 1, 1);
}
public int recursive(int n, int max, int lower, int current) {
// // for your convenience
// System.out.println("n:" + n + " max:" + max + " lowerbound:" + lower + " current:" + current);
// Base case
if (n <= 1 && lower == max) {
return 1;
}
// Recursive step
// Sequence complete, move to next column
if (current == max) {
// Make sure the lower bound does not go beyond the max. number
int updatedLower = (lower + 1 > max) ? lower : lower + 1;
return 1 + recursive(n - 1, max, updatedLower, updatedLower);
}
return 1 + recursive(n, max, lower, current + 1);
}
In short:
In the second example:
n=2
max=3
{1,1}
{1,2}
{1,3}
{2,2}
{2,3}
{3,3}
Note the pattern of the numbers that appears due to the rule that the numbers from left to right have to be equal or larger:
Second column: 1>2>3 > 2>3 > 3
First column: 1>1>1 > 2>2 > 3
The 'lower bound' parameter in the recursion is basically the lowest possible number the new 'sequence' can take (where each sequence is lower bound -> max number). The base case is then when the lower bound equals the upper bound and each column has done all it 'sequences'. Possibly not a very clear explanation - maybe it helps when you see what is printed out by the commented line in the code I copy pasted.
Note: Maybe it is possible to do the recursion with less parameters. Make sure to read a lot about recursion (for example wikipedia or your studybook?). Recursions makes it easier to find solutions and understand complex and abstract problems.
I have write some less efficient code due to time, try look at this, it will give you dir, i hope,
package com.exercise;
import java.util.Arrays;
public class Permutation {
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
private static void permutationOnInt(String prefix, String str, int max) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i <= n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
public static int[] return_Array(int length) {
int[] a = new int[length];
for (int i = 0; i < length; i++) {
a[i] = i + 1;
}
return a;
}
public static void main(String[] args) {
String fn = Arrays.toString(return_Array(3));
String apple = String.join(",", fn.replace("[", "").replace("]", "").replace(",", "").replaceAll("\\s+", ""));
permutationOnInt("", apple, 3);
}
}
After you get the result you can convert it back to the array.
Importent : This code is totally not optimized. I will post optimized later

Resolving Stacks with Return Statements

Although I think I have a solid understanding of resolving stacks in void methods, return methods really mess up my understanding of stacks. The following method particularly confuses me as I would have thought that it would return 0, but returns 12 instead.
public static int mystery(int n) { // where the method call is mystery(7)
n--; // since n is decremented before the first
// recursive method, the first stack is method(6)
if(n > 0) // base case
mystery(n);
return n * 2; // 0 * 2 = 0?
}
My question is why does the method output 12 when mystery(7), if 0 is the last value to go into the stack. Wouldn't this method still follow LIFO?
This has to be like this:
public static int mystery(int n) { // where the method call is mystery(7)
n--; // since n is decremented before the first
// recursive method, the first stack is method(6)
if(n > 0) // base case
n = mystery(n);
return n * 2; // 0 * 2 = 0?
}
Now it will return 0 always.
From the inside out:
The innermost call to mystery (n is 1 on entry) returns 0 to its caller. The return value is not used.
The next level of mystery (n is 2 on entry) returns 2 to its caller. The return value is not used.
...and so on...
The next-to-outermost level of mystery (n is 6 on entry) returns 10 to its caller. The return value is not used.
The outermost level of mystery (n is 7 on entry) returns 12 to its caller, which is the final return value.
Let's not consider 7. Let's say your value is 3. mystery(3). In this case, the function will run 3 times.
First run:
n = 3;
n--; // n = 2
(n > 0) so mystery(2)
Second run:
n = 2;
n--; // n = 1
(n > 0) so mystery(1)
Third run:
n = 1;
n--; // n = 0
(n = 0) so return the n*2 . And the return will be 4
Why? Cause the recursive function does not change the value of n

Finding Geometric sum using recursion

I am trying to better understand recursion. I am writing a basic geometric series method which I know could be done easier with a loop but that is not the purpose. The method is producing the currect output for the values of 0 and 1 which is simply 1 and 1.5. But for 2 it is outputting 1.25 when it should be 1.75. Any pointers on a better way to approach this?
public static double geometricSum(int n) {
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((int) (1/Math.pow(2, n)));
}
This happens because you are casting a float into a int.
1/(2^2)=1/4=0.25 --> 0
As you are passing your float as an int you're not getting your thing working propperly.
So 0.25 + geometricSum(0)=1.25.
On the first one happens the same. you pass the 0.5, but turned into an int so you.re not getting your aproximation propperly done.
As an advice, ALWAYS put () on your math functions in order to make the program, and you yourself, understand in which order it computes the numbers.
The first problem is the cast to int, giving the wrong result, already described by reyeselda95.
There is a second problem hidden, which is that if you fix that you get this:
public static double geometricSum(double n) {
System.err.println("Calling with " + n);
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((1/Math.pow(2, n)));
}
Calling this with the provided value of 2, leads to a loop between calls with the following values, leading to a stack overflow.
...
Calling with 0.4999999999999999
Calling with 0.5000000000000001
Calling with 0.4999999999999999
Calling with 0.5000000000000001
...
This may be the function you are looking for, if I understand correctly:
public static double geometricSum(int count) {
if (count == 0) {
return 1;
}
return geometricSum(count-1) + Math.pow(2, -count);
}
Don't cast float to int;
When using float, are you sure your formula is correct? The recursion breaks if an argument is zero, but you will get StackOverflowError when passing the result of 1.0/Math.pow(2, n) to the function.
This is my python code:
def geometricSum(k):
if k == 0:
return 1
return 1/2**k + geometricSum(k-1)
k = int(input())
print(geometricSum(k))
This is all about the power of 2 i.e. 2 Pow n where n is an integer.
Here Recursion is used to get the sequence of values for n.
In my case I've to calculate the value for 1/(2 pow n).

Method to return a fractal sequence (1 12 123 1234 ...) as a string, but last sequence is printing twice. (Java)

The point of this program is to return a "fractal sequence" up until some number, n. That sounds fancy, but all it means is that if, say, n = 4, then it would return: 1 1 2 1 2 3 1 2 3 4. (It just counts up to 1, then 2, then 3, then 4, and returns each step as it gets there.) To make it easier to see: 1 12 123 1234.
The method is called "foo", and the main method must print it. So, the main method calls it by going System.out.print(foo(4)).
The foo method must return a string.
Loops may appear in the foo method, but the point of the exercise is to solve the problem recursively, and so the bulk of the work is supposed to feature a recursion. Or else, this would be a lot easier with some for loops!
public class test{
public static void main(String args[]){
System.out.print(foo(4));
}
public static String foo(int n){
String s = "";
if(n == 1){ //Base step of the recursion
s = 1 + " ";
}
else{
s = foo(n-1) + n + " "; //Recursive step of the recursion
}
System.out.print(s);
return s;
}
}
Right now, what the program will print is 1 1 2 1 2 3 1 2 3 4 1 2 3 4.
The problem is that it is printing out an extra set of 1 2 3 4 at the end. I realize the reason why it's doing that is because System.out.print(s) prints out everything I need, but then the extra System.out.print(foo(4)) in the main method is printing out the extra 1 2 3 4 at the end.
This could easily be solved if in the main method, I just took out System.out.print, and just wrote foo(4);. But, like rule (1) says, the main method must have the print. I'm not allowed to edit anything outside the foo method.
I have tried a bunch of different things (for about 7 hours or so now), but I don't seem to be "getting it". Can someone shed light on where I am going wrong?
Thank you sincerely!
I first thought about an iterative solution to this.
//Iterative Solution
public static String bar(final int n){
final StringBuilder builder = new StringBuilder();
for (int i = 1; i <= n ; i++) {
for (int j = 1; j <= i ; j++) {
builder.append(j);
}
builder.append(" ");
}
return builder.toString();
}
The fact that this relies on 2 nested loops suggests to me that it is not possible to produce a recursive solution using only a single method and no loops. So I've had to include a loop to build up the individual sections within the recursion.
//Recursive Solution (with some iteration too)
public static String foo(final int n) {
if( n == 1 ) {
return 1 + " ";
}
String s = "";
for (int i = 1; i <= n; i++) {
s += i;
}
return foo(n-1) + s + " ";
}
Both of these produce the same output when called with 4, so my main method:
public static void main(final String args[]){
System.out.println(bar(4));
System.out.println(foo(4));
}
Produces this output:
1 12 123 1234
1 12 123 1234
Change the method to:
public static String foo(int n){
String s = "";
if( n <= 0 ) { //Base step of the recursion
s = "";
}
else {
String foo = foo(n-1);
s = foo + foo.substring(foo(n-2).length(), foo.length() -1) + n + " "; //Recursive step of the recursion
}
return s;
}
[Edit]:
Explanation:
What we need here is an accumulator. However, just using foo(n-1) + n will just give us the sequence 12345. So we need to get the last part of the n-1 sequence to get the full 1 12 123 1234 ... I have not tested this code, maybe you need to use foo.substring(foo.length - n, foo.length), but i thought n-1 should be correct. This just retrieves the last sequence ( 123 from 112123 ).
I changed the boundaries because i forgot the space.
With space:
s = foo + foo.substring(foo.length()- n, foo.length() -1) + n + " ";
Without space:
s = foo + foo.substring(foo.length()- (n-1), foo.length()) + n;
[Edit 2]
Didn't work for values n > 10, the new version uses foo(n-2) to figure out the substring. Note that this changes the complexity class for the worse. A better version would either be iterative and use dynamic programming, or use Integer Lists instead of Strings.
This should work:
pulic class test {
public static void main(String args[]) {
System.out.print(foo(4));
}
public static String foo(int n) {
String s = "";
if(n == 0) { //do nothing
}
else {
s = foo(n-1);
System.out.print(s);
s=s+n;
}
return s;
}
}
Right now you are printing the result of the recursion as well as each step. As the result is "1 2 3 4" you get this doubled.
1 for `System.out.print(s);` on step 1
1 2 for `System.out.print(s);` on step 2
1 2 3 for `System.out.print(s);` on step 3
1 2 3 4 for `System.out.print(s);` on step 4
1 2 3 4 for `System.out.print(foo(4));`
so calling foo(4); will get the result you want

Categories

Resources