How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Wren programming language
Table of Contents
Problem Statement
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Wren programming language
Source code in the wren programming language
import "./math" for Int
var LIMIT = 999999
var primes = Int.primeSieve(LIMIT)
var longestSeq = Fn.new { |dir|
var pd = 0
var longSeqs = [[2]]
var currSeq = [2]
for (i in 1...primes.count) {
var d = primes[i] - primes[i-1]
if ((dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd)) {
if (currSeq.count > longSeqs[0].count) {
longSeqs = [currSeq]
} else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)
currSeq = [primes[i-1], primes[i]]
} else {
currSeq.add(primes[i])
}
pd = d
}
if (currSeq.count > longSeqs[0].count) {
longSeqs = [currSeq]
} else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)
System.print("Longest run(s) of primes with %(dir) differences is %(longSeqs[0].count):")
for (ls in longSeqs) {
var diffs = []
for (i in 1...ls.count) diffs.add(ls[i] - ls[i-1])
for (i in 0...ls.count-1) System.write("%(ls[i]) (%(diffs[i])) ")
System.print(ls[-1])
}
System.print()
}
System.print("For primes < 1 million:\n")
for (dir in ["ascending", "descending"]) longestSeq.call(dir)
You may also check:How to resolve the algorithm Strip block comments step by step in the Ksh programming language
You may also check:How to resolve the algorithm Singly-linked list/Element definition step by step in the OCaml programming language
You may also check:How to resolve the algorithm Morse code step by step in the Phix programming language
You may also check:How to resolve the algorithm Parsing/Shunting-yard algorithm step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Wordle comparison step by step in the FreeBASIC programming language