Sum of primes in odd positions is prime

From Rosetta Code
Revision as of 14:36, 1 September 2021 by PureFox (talk | contribs) (Added Go)
Sum of primes in odd positions is prime is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task


Let p(i) be a sequence of prime numbers.
Consider the p(1),p(3),p(5), ... ,p(i), for each p(i) < 1,000 and i is odd.
Let sum be summarize of these primes.
If sum is prime then print p(i) and sum



Factor

Works with: Factor version 0.99 2021-06-02

<lang factor>USING: assocs assocs.extras kernel math.primes math.statistics prettyprint sequences.extras ;

1000 primes-upto <evens> dup cum-sum zip [ prime? ] filter-values .</lang>

Output:
{
    { 2 2 }
    { 5 7 }
    { 31 89 }
    { 103 659 }
    { 149 1181 }
    { 331 5021 }
    { 467 9923 }
    { 499 10909 }
    { 523 11941 }
    { 653 17959 }
    { 823 26879 }
}

Go

Translation of: Wren
Library: Go-rcu

<lang go>package main

import (

   "fmt"
   "rcu"

)

func main() {

   primes := rcu.Primes(999)
   sum := 0
   fmt.Println(" i   p[i]  Σp[i]")
   fmt.Println("----------------")
   for i := 0; i < len(primes); i += 2 {
       sum += primes[i]
       if rcu.IsPrime(sum) {
           fmt.Printf("%3d  %3d  %6s\n", i+1, primes[i], rcu.Commatize(sum))
       }
   }

}</lang>

Output:
 i   p[i]  Σp[i]
----------------
  1    2       2
  3    5       7
 11   31      89
 27  103     659
 35  149   1,181
 67  331   5,021
 91  467   9,923
 95  499  10,909
 99  523  11,941
119  653  17,959
143  823  26,879

Ring

<lang ring> load "stdlib.ring" see "working..." + nl see "p" + " sum" + nl

nr = 0 sum = 0 limit = 1000

for n = 2 to limit

   if isprime(n)
      nr++
      if nr%2 = 1
         sum += n
         if isprime(sum)
            see "" + n + " " + sum + nl
         ok
      ok
   ok

next

see "done..." + nl </lang>

Output:
working...
p  sum
2 2
5 7
31 89
103 659
149 1181
331 5021
467 9923
499 10909
523 11941
653 17959
823 26879
done...

Wren

Library: Wren-math
Library: Wren-trait
Library: Wren-fmt

<lang ecmascript>import "/math" for Int import "/trait" for Indexed import "/fmt" for Fmt

var primes = Int.primeSieve(999) var sum = 0 System.print(" i p[i] Σp[i]") System.print("----------------") for (se in Indexed.new(primes, 2)) {

   sum = sum + se.value
   if (Int.isPrime(sum)) Fmt.print("$3d  $3d  $,6d", se.index + 1, se.value, sum)

}</lang>

Output:
 i   p[i]  Σp[i]
----------------
  1    2       2
  3    5       7
 11   31      89
 27  103     659
 35  149   1,181
 67  331   5,021
 91  467   9,923
 95  499  10,909
 99  523  11,941
119  653  17,959
143  823  26,879