Stern-Brocot sequence: Difference between revisions

m
→‎While loop: Improved syntax.
m (→‎{{header|R}}: Syntax highlighting.)
m (→‎While loop: Improved syntax.)
Line 4,907:
 
As with the previous solution, we have used a library for our gcd function. In this case, we have used gmp.
<lang rsplus>genNStern <- function(n)
{
sternNums <- c(1L1,1L 1)
i <- 2
while((endIndex <- length(sternNums)) < n)
{
#To show off R's vectorization, the following line is deliberately terse.
Line 4,918:
#Note that we do not have to initialize a big sternNums array to do this.
#True to the algorithm, the new entries are appended to the end of the old sequence.
sternNums[endIndex + c(1, 2)] <- c(sum(sternNums[c(i - 1, i)]), sternNums[i])
i <- i + 1
}
sternNums[1:seq_len(n)]
}
#N=5000 was picked arbitrarily. The code runs very fast regardless of this number being much more than we need.
firstFiveThousandTerms <- genNStern(5000)
match(1:10, firstFiveThousandTerms)
match(100, firstFiveThousandTerms)
all(sapply(1:999, function(i) gmp::gcd(firstFiveThousandTerms[i], firstFiveThousandTerms[i + 1])) == 1)</lang>
{{Output}}
<pre>> firstFiveThousandTerms <- genNStern(5000)
> match(1:10, firstFiveThousandTerms)
[1] 1 3 5 9 11 33 19 21 35 39
> match(100, firstFiveThousandTerms)
[1] 1179
> all(sapply(1:999, function(i) gmp::gcd(firstFiveThousandTerms[i], firstFiveThousandTerms[i + 1])) == 1)
[1] TRUE</pre>
 
331

edits