how to move to the next loop in PARI/GP if I use multi-line nested for loops? - pari-gp

my question is: how to move to the next loop in PARI/GP if I use multi-line nested for loops ? for example :
if I use this code :
for(K=1,10,for(i=1,5,if(isprime(2*i*prime(K)+1)==1,print(2*i"*"prime(K)))))
and since 2*(i=1)*prime(K=1)+1=5 is prime, I need my machine not to loop for i=2......i=5, I need it to move on to the next K, so:
how to do this on PARI/GP?
and I am sorry if my question is not clear or duplicated.

You need to use break. But first, let's clean up the presentation so this is more readable:
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1)==1,
print(2*i"*"prime(K))
)
)
);
}
func()
You want to break out of the innermost loop, like so (just giving the function itself):
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1)==1,
print(2*i"*"prime(K));
break
)
)
);
}
But while we're here, there's no need to add == 1; if is already branching on nonzero values.
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1),
print(2*i"*"prime(K));
break
)
)
);
}
We could also store the value of prime(K) so we don't need to compute it twice. But better yet, let's use a loop directly over the primes so we don't need the prime() function at all!
func(maxK=10)=
{
my(K=0);
forprime(p=2,prime(maxK),
K++;
for(i=1,5,
if(isprime(2*i*p+1),
print(2*i"*"p);
break
)
)
);
}
Here I have changed the function so you can call it with different maximum values other than 10 and I've kept the index in case you wanted it for some reason. But I think a better approach would be to give a bound on how high you want to go in the primes directly, and forgetting about the prime indexes entirely:
func(maxP=29)=
{
forprime(p=2,maxP,
for(i=1,5,
if(isprime(2*i*p+1),
print(2*i"*"p);
break
)
)
);
}
In both cases I added a default argument so calling func() will do the same thing as your original function (except that it now breaks the way you want).

Related

What is the equivalent of 'break' in q#?

How would I break out of a loop when I meet a condition?
For example:
for (i in 0..10){
if (i==3){
// equivalent of break
}
}
There is no break in Q#; however, you can implement this behavior using repeat-until-success loop.
Q# is not a general-purpose language, and is designed to allow a lot of optimizations for when a program will be executed on a quantum device. Loops are one example of such design: if you know beforehand how many iterations your loop will do, use a for loop, if you need to iterate until some condition is met, use repeat-until-success loop.
Your example (which is not really a good example of why you'd need a break) would be written as something like this:
mutable i = 0;
repeat {
set i = i + 1;
} until (i == 10 || i == 3)
fixup {
();
}

R - Writing a function to return binary output using if statement

Good day,
I am a beginner and trying to understand why I am getting the error below.
I am trying to create a function that would return 0 or 1 based on column values in data set.
LT = function(Lost.time) {
For (i in 1:dim(df)) {
if (df$Lost.time > 0) {
x = 1
}
else {
x = 0
}
return(x)
}
}
Error: no function to return from, jumping to top level In addition: Warning
message: In if (df$Lost.time > 0) { : the condition has length > 1 and only
the first element will be used> } Error: unexpected '}' in "}"
There are a couple of mistakes in the code:
R is case sensitive. Use for instead of For.
If you are looping over the entries in df$Lost.time, the individual elements should be addressed within the loop using df$Lost.time[i]. However, a loop is not necessary for this task.
An else statement should not begin on a new line of the code. The parser cannot know that the if statement is not finished after the first block. If the else statement is enclosed in curly braces like in } else { there will be no problem in this sense.
The parameter passed to the function is not suitable. Maybe you could pass df, instead of Lost.time, but it may be necessary to rewrite parts of the function.
The use of 1:dim(df) in the for loop should work, but it will trigger a warning message. It is better to use 1:nrow(df).
Those are syntax problems. However, the main issue is probably what has been addressed in the answer by #TimBiegeleisen: In the loop you are checking for each of the ̀nrow(df) elements of df$Lost.time whether a specific condition is fulfilled. It therefore does not seem to make sense to have a single binary result as return value. The purpose of the function should be clarified before it is implemented.
An alternative to this function could be constructed in a one-liner with ifelse.
It is not clear what you actually want to return in your function. return can only be called once, after which it will return a single value and the function will terminate.
If you want to get a vector which will contain 1 or 0 depending on whether a given row in your data frame has Lost.time > 0, then the following one liner should do the trick:
x <- as.numeric(df$Lost.time > 0)
If loops are used for writing a function indices should be used for each element.
Create a variable(x) in your dataframe, if the statements goes true it prints 1 else 0
LT = function(Lost.time) {
for (i in 1:dim(df)) {
if (as.numeric(df$Lost.time[i]) > 0) {
df$x[i] <- 1
}else{
df$x[i] <- 0
}
}
}

How to "leap of faith" when using recursion?

For me when making a recursive method. I always need to spend a lot of time to do it, because I will make some test cases and to see whether my recursive case works and to draw a stack diagram. However, when I ask other about it, they just say that I need to believe myself it will work. How am I suppose to believe that if you don't know what is going on in the recursive case?
You define what is going on in the recursive case, just as you define the rest of the method. Imagine someone else wrote a method to do what the one you are writing does; you wouldn't have a problem calling that, would you? The only difference is that you are that method's author, and it just happens to be the one being written.
For example: I am writing the following method:
// Sort array a[i..j-1] in ascending order
method sort_array( a, i, j ) {
..
}
The base case is easy:
if ( i >= j-1 ) // there is at most one element to be sorted
return; // a[i..j-1] is already sorted
Now, when that isn't true, I could do the following:
else {
k = index_of_max( a, i, j );
swap( a, j-1, k );
At this point, I know that a[j-1] has the correct value, so I just need to sort what comes before it -- fortunately, I have a method to do just that:
sort_array( a, i, j-1 );
}
No leap of faith is required; I know that recursive call will work because I wrote the method to do just that.

Recursively wrapping up an element

Say I have an element <x>x</x> and some empty elements (<a/>, <b/>, <c/>), and I want to wrap up the first inside the second one at a time, resulting in <c><b><a><x>x</x></a></b></c>. How do I go about this when I don't know the number of the empty elements?
I can do
xquery version "3.0";
declare function local:wrap-up($inner-element as element(), $outer-elements as element()+) as element()+ {
if (count($outer-elements) eq 3)
then element{node-name($outer-elements[3])}{element{node-name($outer-elements[2])}{element{node-name($outer-elements[1])}{$inner-element}}}
else
if (count($outer-elements) eq 2)
then element{node-name($outer-elements[2])}{element{node-name($outer-elements[1])}{$inner-element}}
else
if (count($outer-elements) eq 1)
then element{node-name($outer-elements[1])}{$inner-element}
else ($outer-elements, $inner-element)
};
let $inner-element := <x>x</x>
let $outer-elements := (<a/>, <b/>, <c/>)
return
local:wrap-up($inner-element, $outer-elements)
but is there a way to do this by recursion, not decending and parsing but ascending and constructing?
In functional programming, you usually try to work with the first element and the tail of a list, so the canonical solution would be to reverse the input before nesting the elements:
declare function local:recursive-wrap-up($elements as element()+) as element() {
let $head := head($elements)
let $tail := tail($elements)
return
element { name($head) } { (
$head/#*,
$head/node(),
if ($tail)
then local:recursive-wrap-up($tail)
else ()
) }
};
let $inner-element := <x>x</x>
let $outer-elements := (<a/>, <b/>, <c/>)
return (
local:wrap-up($inner-element, $outer-elements),
local:recursive-wrap-up(reverse(($inner-element, $outer-elements)))
)
Whether reverse(...) will actually require reversing the output or not will depend on your XQuery engine. In the end, reversing does not increase computational complexity, and might not only result in cleaner code, but even faster execution!
Similar could be achieved by turning everything upside down, but there are no functions for getting the last element and everything before this, and will possibly reduce performance when using predicates last() and position() < last(). You could use XQuery arrays, but will have to pass counters in each recursive function call.
Which solution is fastest in the end will require benchmarking using the specific XQuery engine and code.

call answer from a previous function

I'm trying to write a function in R that will return as its output, an one output from a previous function. The previous function returns a list of 3 different things.
So far the only way I've worked out how to do this is completely copy and paste the original function, and get it to return only one answer, but surely there is a shorter way in which to do this?
If the original function is named foo(), as in
foo <- function ( something ) {
# some code
return(list(residuals, residualssquared,tss))
}
then just do
bar <- function ( something ) {
return ( foo(something)$tss )
}
or simply use foo(something)$tss to directly access the tss component of the return value of foo(). There is really no need to wrap another function bar() around foo().

Resources