Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm new to R programming and I am struggling to find the next prime number given some number x. I have tried the logic in Java and it works. So what I really did was to translate some Java code to R. So here is my Java version that works.
public static int nextPrime(int n) {
int i,j;
for( i= n+1;;i++) {
for(j=2;j<i;j++) {
if(i % j == 0)
break;
}
if(j == i) {
// System.out.println(i);
break;
}
}
return i;
}
and here is my R version
nextPrime <- function(x) {
i = x+1
repeat {
for(j in 2 : (i-1)) {
if((i %% j) == 0 ) {
break
}
# j = j+1
# print(j)
}
if( i == j){
break
}
i = i+1
}
print(i)
}
nextPrime(11)
I don't know about Java, but here is a function - while loop - that gives you what you want.
f <- function(x){
# #IsmailMüller
temp <- x+1
test <- 2:x
# while temp is divisible by at least one precedent value (not prime)
while( any( (temp %% test) == 0 ) ){
# increase the value of temp by 1
temp <- temp+1
}
temp
}
f(11)
Following your code, both are not same.
Replace
for(j in 2 : (i-1))
With
for(j in 2 : i)
Related
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 8 months ago.
Improve this question
// Add edges
public void addEdge(int i, int j) {
adjMatrix[i][j] = true;
adjMatrix[j][i] = true;
}
// Remove edges
public void removeEdge(int i, int j) {
adjMatrix[i][j] = false;
adjMatrix[j][i] = false;
}
// Print the matrix
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < numVertices; i++) {
s.append(i + ": ");
for (boolean j : adjMatrix[i]) {
s.append((j ? 1 : 0) + " ");
}
s.append("\n");
}
return s.toString();
}
Explain the following line in the code:
for (boolean j : adjMatrix[i]) {
s.append((j ? 1 : 0) + " ");
the enhanced for loop using boolean operator is not clear.
How to understand it and how does it work?
The above code is taken by programiz.com.
The above code is related to adjacency matrix.
Take a Example
adjMatrix = [
[true , false , true],
[false , false , true],
[true , true , false]
]
Step 1: Iterating through each row of matrix
WHEN i = 0
for (boolean j : [true , false , true]) {
s.append((j ? 1 : 0) + " ");
Step 2: Iterating through each boolean element of a row
Value of j in each iteration will be:
Step 3 AND 4: Appending in S(variable)
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 1 year ago.
Improve this question
The below pattern code is not working as expected.
public class pattern_print {
public static void main (String args[]){
int i = 1, j = 5, n = 5;
while (i <= n) {
while (j >= i) {
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
}
}
Who can help me?
What are you expecting?
The code that you wrote is displaying the following chars:
*****
If you want to display something like:
*****
****
***
**
*
Then the correct code is:
public class pattern_print {
public static void main (String args[]) {
int i = 1, j = 5, n = 5;
while (i <= n) {
while (j >= i) {
System.out.print("*");
j--;
}
System.out.print("\n");
j=5;
i++;
}
}
}
Now depends what you expect to be displayed.
If the following triangle pattern is expected:
*****
****
***
**
*
the value of j needs to be reset to n as Andreea Frincu suggested.
However, for loops may be more preferable when printing patterns.
Also, since Java 11 released back in Sep 2018 there is method String::repeat which allows to avoid redundant nested loops and the same triangle pattern may be printed as simply as:
for (int i = 5; i >= 0; i--) {
System.out.println("*".repeat(i));
}
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
I am new to programming and would appreciate any experts to provide suggestions.
Based on the given flowchart, am I on the right track?
How do I make improvement to my code to ensure robustness?
Flowchart
Code
// r is row, c is column
int r = 1, c = 1;
do {
if (r <= 4)
{
if (c <= 10)
{
System.out.print("*");
c += 1;
}
else {
r += 1;
c = 1;
System.out.println();
}
}
else {
System.exit(1);
}
}while (c != 12);
Output
**********
**********
**********
**********
while (c != 12);
The flow chart doesn't have this condition.
Notice how your if (r <= 4) statement is directly nested in the do...while. This means you can reduce to a single while:
while (r < = 4) {
...
}
Similarly c <= 10 should be implemented as a loop instead of just an if.
The flow chart doesn't say to do start a new line like you do with System.out.println();. So taken literally, this line is incorrect. However, I suspect the flow chart omitted this detail and is in error.
According to the algorithm proposed, its code is seen to follow or comply with the guideline.
Your code looks great, it just tries to name the variables in a more similar way to what you are trying to replicate.
I have tried to shorten the number line of coding.
int row = 1, column = 1;
while (row <= 4)
{
if (column <= 10) {
System.out.print("*");
column += 1;
}
else {
row += 1;
column = 1;
//System.out.println();
}
}
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 6 years ago.
Improve this question
I'm new in Java.
I have next code:
public static void main(String[] args) {
for(int k = 10; k > 0; k--)
{
for(int l=0; l < k-1; l++)
{
System.out.print(' ');
}
for(int n=10; n > k-1; n--)
{
System.out.print('*');
}
System.out.println();
}
}
It prints this:
*
**
***
****
*****
******
*******
********
*********
**********
But I want to print it with empty inside like this:
*
**
* *
* *
* *
* *
* *
* *
* *
**********
Can anyone to explane me how to do it.
I understand that this is not a place where solve homework tasks. But can somebody tell me the algorithm for solving the problem in words.
I do not need a ready solution because I want to understand and solve it by myself. So how I can put spaces inside?
Hint: In the second loop you should print a '*' for the first and last values of n, not all of them. For the other positions, print a ' '.
Hint: in the second inner for loop, you could have an if statement where you check for n's greatest and lowest values, and k's lowest value, then print a '*', otherwise print a ' '. Like so:
for(int n = 10; n > k - 1; n--){
if(n == 10 || n == k || k == 1){
System.out.print('*');
} else {
System.out.print(' ');
}
}
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 8 years ago.
Improve this question
I have three for loops, and I wish to turn them into recursive method because I want to do this for any amount of for loops. I searched online, but nobody seems to have exactly what I need, for example this guy turns recursion into for loops
Turning a recursive function into a for loop?
Code:
int x = 3;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++){
list.add(array[i] + array[j] + array[k]);
}
}
}
Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.
Like this:
Object loop(int i, Object data) {
if (i > 0) {
return loop(i - 1, evolve(data));
} else {
return data;
}
}
That's the same as this:
for ( ; i > 0; i--) {
data = evolve(data);
}
In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.
In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.
Haters aside, let's do this! [1]
Given:
int x = 3;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++){
list.add(array[i] + array[j] + array[k]);
}
}
}
Let's consider that each loop is it's own recursive function - as this makes the recurrence cases much easier! This is also the only "non-thinking" method I know of to turn the loops into recursion. The recursive depth will be limited to 3*x => i+j+k so it's "fairly safe" for a smallish[2] x.
In Java it requires a separate method for each loop to encode this structure. (In a language with higher-order functions these three functions might be abstractly combined .. but not in Java [7].)
void loopI(int i) {
if (i < x) {
loopJ(0); // "start j loop"
loopI(i++); // "next i loop" / recurrence case
}
// "end loop" / base case
}
void loopJ(int j) {
if (j < x) {
loopK(0);
loopJ(j++);
}
}
void loopK(int k) {
if (k < x) {
list.add(array[i] + array[j] + array[k]);
loopK(k++);
}
}
// do it!
loopI(0);
All of these could be combined into a single recursive function, but that makes handling the recurrence cases a bit tougher as "thinking" and additional conditionals (or mod expressions, perhaps) are required to advance the state.
Here is an example of a combined recursive function (this is incorrect when x is 0). Unlike the three method approach above, the stack depth will grow to x^3 => i*j*k. This will easily kill Java's recursion limits - even for smallish values of x- as Java [7] doesn't have tail-call optimization.
void loop(int i, int j, int k) {
list.add(array[i] + array[j] + array[k]);
// advance states
k++;
if (k == x) { k = 0; j++; }
if (j == x) { j = 0; i++; }
if (i == x) { i = 0; }
// terminate on all wrap-around
if (i == 0 && j == 0 && k == 0) { return; }
// recurse
loop(i, j, k);
}
[1] YMMV, for theoretical purposes only - I love recursion, but it's not suited for this case in Java.
[2] For some value of "smallish". See how deep your stack can go!