Can you explain to me this java code step by step? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This is a code, I don't understand
public class main {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
The result is 55

This is a recursive method.
As long as k > 0, the method will keep calling itself with a smaller value of k.
The initial call, sum(10) returns
10 + sum(9) == 10 + 45 == 55
sum(9) returns
9 + sum(8) == 9 + 36 == 45
sum(8) returns
8 + sum(7) == 8 + 28 == 36
...
sum(2) returns
2 + sum(1) == 2 + 1 == 3
sum(1) returns
1 + sum(0) == 1 + 0 == 1
sum(0) returns 0.
Therefore the method returns the sum of all integers between 0 and 10, which is 55.

Related

Understanding code to find the largest prime factor of a number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I found this code on an old youtube video and am having the hardest time understanding the logical sequence for the output. I was hoping any of you can help clarify.
Let's assume I pass a value of 21 to the getLargestPrime method.
In line 17 the conditional statement checks whether 21 % 2 != 0, that's True. So it carries another iteration of the code. But this time m = 3, which 21 % 3 != 0, that's actually False. Why is the code still executing the else statement? This is question #1.
Question #2
How can the if statement inside the else ever execute? When does number become == 1?
I know that this is probably super basic for you guys but for some reason I cannot follow the sequence in the output.
public class LargestPrime {
public static int getLargestPrime(int number){
if(number < 0){
return -1;
}
int m = 2;
int ans = 0;
int numbern;
if(number == 1){
System.out.println("This number is not a prime");
} else{
while (ans == 0){
if(number % m !=0){
m = m +1;
System.out.println(m + " value of m");
} else {
numbern = number;
number = number / m;
if(number == 1){
System.out.println(numbern + " is the largest prime factor of your number");
ans++;
}
}
}
} return number;
}
}
This is the output:
3 value of m
4 value of m
5 value of m
6 value of m
7 value of m
7 is the largest prime factor of your number
1
21%3!=0 returns false. Because of this the jvm executes the code after else. In e.g. 21%2!=0, that is true, it executes the code after if.
It is 1, if number is as m.
This is when your calculation gets to an end because there cannot be any more numbers after your number.

How can I check for prime numbers? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is the simplest way to do this, preferably without lists or maps?
I've tried turning the wikipedia pseudocode into real code but I don't understand the second half after the new line at all.
function is_prime(n : integer)
if n ≤ 1
return false
else if n ≤ 3
return true
else if n mod 2 = 0 or n mod 3 = 0
return false
let i ← 5
while i×i ≤ n
if n mod i = 0 or n mod (i + 2) = 0
return false
i ← i + 6
return true
First off, here's that function converted to java:
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
} else if (n <= 3) {
return true;
} else if (n % 2 == 0 || n % 3 == 0) {
return false;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
i += 6;
}
return true;
}
The second half is the part that iterates from the lowest unchecked number (5, because multiples of 2 are already checked, as are 0, 1, and 3) to the square root of n (anything greater than the square root would have to be multiplied by something less than the square root to equal n), checking each number i to see if n is evenly divisible by i.
try this code
public static boolean isPrime(int n) {
for (int i = 2; i < n - 1; i++) {
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPrime(39));
}

Tracing through a recursive function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
For the following code segment, I am having trouble tracing through it (which I need to be able to do for my upcoming test.
public int question(int x, int y)
{
if (x ==y)
return 0;
else
return question(x-1, y) + 1;
}
I am also confused as to what the + 1 is doing. What is 1 being added on to. I know the result is five, but I need to be able to better understand the concept. Thanks for your help.
Basically:
question(8,3) will return question(7,3) + 1
question(7,3) will return question(6,3) + 1
question(6,3) will return question(5,3) + 1
question(5,3) will return question(4,3) + 1
question(4,3) will return question(3,3) + 1
and question(3,3) is 0.
It should be obvious that the result of question(8,3) is 5 by simple substitution. It should be noted that if x < y then you might get a stack overflow as x keeps decrementing and will possibly never get to x == y.
the 1 is being added onto the return from the function every time the function recurses 1 is added onto the return of int
public int question(int x, int y)
{
if (x ==y)
return 0;
else
return question(x-1, y) + 1;
}
say you call
int result = question(5,0);
since your general case calls
return question(x-1, y) + 1;
the + 1 is going to recurse until you hit the base case of
if (x ==y)
return 0;
giving you +1 +1 +1 +1 +1 +0
until x = 0 and y = 0
You can always add a couple prints to the method to better understand what it is doing:
static int question(int x, int y) {
if (x ==y) {
System.out.println(x + " == " + y);
System.out.println("return 0");
return 0;
} else {
System.out.println(x + " != " + y);
System.out.println("call question(" + (x - 1) + ", " + y + ")");
int result = question(x - 1, y);
System.out.println("return " + result + " + 1");
return result + 1;
}
}
Then call it. For example:
public static void main(String... args) {
System.out.println(question(8, 3));
}
Output:
8 != 3
call question(7, 3)
7 != 3
call question(6, 3)
6 != 3
call question(5, 3)
5 != 3
call question(4, 3)
4 != 3
call question(3, 3)
3 == 3
return 0
return 0 + 1
return 1 + 1
return 2 + 1
return 3 + 1
return 4 + 1
5
In order to understand recursion, try to write function in a mathematical way. I will first demonstrate this with the classic factorial, then explain you the example you gave.
Let fact(n) be n!. The recursive definition of factorial is:
fact(n) = 1, if n <= 1
fact(n) = n * fact(n - 1)
Note that we have 2 cases: a base case, which is a simple case that can be calculated directly, and a step case, which requires the value of a recursive call. Note that in order for the recursion to work, the recursive function call should be simpler, in order to move towards the step case. This can be implemented easily in Java:
public int factorial(int n)
{
if (n < 2)
return 1;
else
return n*factorial(n-1);
}
Returning to your function, you have to do the same process backwards. We can easily identify the 2 base cases as the branches of if:
Base case: question(x, y) = 0, if x = y
Step case: question(x, y) = question(x - 1, y) + 1, otherwise
It can be noticed that at each recursive call you subtract 1 from x and add 1 to the result. Let's unroll the recursion for question(8, 3):
question(8, 3) = question(7, 3) + 1 // You are in the step case
question(7, 3) = question(6, 3) + 1
question(6, 3) = question(5, 3) + 1
question(5, 3) = question(4, 3) + 1
question(4, 3) = question(3, 3) + 1
question(3, 3) = 0 // The base case
Now, if you replace the value of question(3, 3) in the value of question(4, 3) and do the same upwards, you find out that the result is 8.
There is no straight way to do this, but you can notice that the first parameter is decreasing by 1 and each time this is done, the result increases by 1, until the parameters are equal. Using some intuition, you may notice that this basically computes x - y.
Note that this method requires x >= y, otherwise it will crash.

How to write the code in java to get the desired output? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
If the value of x is 29 then the desired output is 0
If the value of x is 3 then the desired output is 1
If the value of x is 1 then the desired output is 4
If the value of x is 2 then the desired output is 2
You could use if/else or switch statement or a Random number generator.
public static void main(String... args) {
for (int i : new int[] { 29, 3, 1, 2, -2})
System.out.println(i+": "+puzzle(i));
}
public static int puzzle(int n) {
return new Random(3147 * n).nextInt(7) - 2;
}
prints
29: 0
3: 1
1: 4
2: 2
-2: -2
The real question should be; What does the person marking this answer expect you to do based on what you have been taught?
public class Program
{
public static int puzzle(int x)
{
if(x == 29)
return 0;
if(x == 3)
return 1;
if(x == 1)
return 4;
if(x == 2)
return 2;
return 0;
}
}

Create triangle with "1" " 0" by for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I write a program in Java to make the following triangle?
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
Try:
String s = "";
for(int i = 0 ; i < nLines ; ++i) {
s = (i % 2 == 0 ? "1 " : "0 ") + s;
System.out.println(s);
}
I don't want to give you a solution, but there's some patterns you can see:
The number of digits is the same as the number of the line, assumign it starts in 1. For example, in the first line, you have 1 digit; in the second you have 2 digits.
If it's an odd line, the first digit is a 1; otherwise, it's a 0.
You always switch between 0 and 1, until you've reached the number of the line.
public class CurvedZebraTriangle{
public static void main(String []args){
int n=5;
for(int i = 0; i <= n; ++i)
{
for(int j = 0; j< i; j++)
System.out.print((i+j) % 2 == 0 ? "0 " : "1 ");
System.out.print("\n");
}
}
}

Categories

Resources