Mian-Chowla sequence: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (Fix misspelling, add a link, remove excess whitespace)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(20 intermediate revisions by 15 users not shown)
Line 64:
:* [[oeis:A005282|OEIS:A005282 Mian-Chowla sequence]]
 
=={{header|11l}}==
{{trans|C++}}
 
<syntaxhighlight lang="11l">F contains(sums, s, ss)
L(i) 0 .< ss
I sums[i] == s
R 1B
R 0B
 
F mian_chowla()
V n = 100
V mc = [0] * n
mc[0] = 1
V sums = [0] * ((n * (n + 1)) >> 1)
sums[0] = 2
V ss = 1
L(i) 1 .< n
V le = ss
V j = mc[i - 1] + 1
L
mc[i] = j
V nxtJ = 0B
L(k) 0 .. i
V sum = mc[k] + j
I contains(sums, sum, ss)
ss = le
nxtJ = 1B
L.break
sums[ss] = sum
ss++
I !nxtJ
L.break
j++
R mc
 
print(‘The first 30 terms of the Mian-Chowla sequence are:’)
V mc = mian_chowla()
print_elements(mc[0.<30])
print()
print(‘Terms 91 to 100 of the Mian-Chowla sequence are:’)
print_elements(mc[90..])</syntaxhighlight>
 
{{out}}
<pre>
The first 30 terms of the Mian-Chowla sequence are:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 to 100 of the Mian-Chowla sequence are:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
</pre>
 
=={{header|Ada}}==
{{works with|Ada|Ada|2012}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Containers.Hashed_Sets;
 
Line 127 ⟶ 177:
Ada.Text_IO.Put(term'Img);
end loop;
end Mian_Chowla_Sequence;</langsyntaxhighlight>
{{out}}
<pre>Mian Chowla sequence first 30 terms :
Line 134 ⟶ 184:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
</pre>
 
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}Allocating a large-enough array initially would gain some performance but might be considered cheating - 60 000 elements would be enough for the task.
<langsyntaxhighlight lang="algol68"># Find Mian-Chowla numbers: an
where: ai = 1,
and: an = smallest integer such that ai + aj is unique
Line 178 ⟶ 227:
FOR i FROM 91 TO 100 DO print( ( " ", whole( mc[ i ], 0 ) ) ) OD
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 187 ⟶ 236:
</pre>
elapsed time approx 0.25 seconds on my Windows 7 system (note under Windows, A68G runs as an interpreter only).
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">mianChowla: function [n][
result: new [1]
sums: new [2]
candidate: 1
 
while [n > size result][
fit: false
'result ++ 0
while [not? fit][
candidate: candidate + 1
fit: true
result\[dec size result]: candidate
loop result 'val [
if contains? sums val + candidate [
fit: false
break
]
]
]
 
loop result 'val [
'sums ++ val + candidate
unique 'sums
]
]
return result
]
 
seq100: mianChowla 100
 
print "The first 30 terms of the Mian-Chowla sequence are:"
print slice seq100 0 29
print ""
 
print "Terms 91 to 100 of the sequence are:"
print slice seq100 90 99</syntaxhighlight>
 
{{out}}
 
<pre>The first 30 terms of the Mian-Chowla sequence are:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 to 100 of the sequence are:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219</pre>
 
=={{header|AWK}}==
Translation of the ALGOL 68 - largely implements the "by hand" method in the task.
<langsyntaxhighlight lang="awk"># Find Mian-Chowla numbers: an
# where: ai = 1,
# and: an = smallest integer such that ai + aj is unique
Line 237 ⟶ 333:
printf( "\n" );
 
} # BEGIN</langsyntaxhighlight>
{{out}}
<pre>
Line 249 ⟶ 345:
===Alternate===
{{trans|Go}}Hopefully the comments help explain the algorithm.
<langsyntaxhighlight lang="awk"># helper functions
#
# determine if a list is empty or not
Line 290 ⟶ 386:
} # for i
print "\n"
} # BEGIN</langsyntaxhighlight>
{{out}}
<pre>Mian Chowla sequence elements 1..30:
Line 301 ⟶ 397:
=={{header|C}}==
{{trans|Go}}
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdbool.h>
#include <time.h>
Line 345 ⟶ 441:
for (int i = 90; i < 100; i++) printf("%d ", mc[i]);
printf("\n\nComputation time was %f seconds.", et);
}</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 356 ⟶ 452:
===Quick, but...===
...is memory hungry. This will allocate a bigger buffer as needed to keep track of the sums involved. Based on the '''ALGOL 68''' version. The minimum memory needed is double of the highest entry calculated. This program doubles the buffer size each time needed, so it will use more than the minimum. The '''ALGOL 68''' increments by a fixed increment size. Which could be just as wasteful if the increment is too large and slower if the increment is too small).
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 405 ⟶ 501:
char buf[100]; approx(buf, nn * sizeof(bool));
printf("\n\nComputation time was %6.3f ms. Allocation was %s.", et, buf);
}</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 427 ⟶ 523:
=={{header|C#|CSharp}}==
{{trans|Go}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 460 ⟶ 556:
string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds);
}
}</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 473 ⟶ 569:
{{trans|Go}}
The '''sums''' array expands by "i" on each iteration from 1 to n, so the max array length can be pre-calculated to the nth triangular number (n * (n + 1) / 2).
<langsyntaxhighlight lang="cpp">using namespace std;
 
#include <iostream>
Line 517 ⟶ 613:
for (int i = 90; i < 100; i++) { cout << mc[i] << ' '; }
cout << "\n\nComputation time was " << et << " seconds.";
}</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 529 ⟶ 625:
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight lang="fsharp">
// Generate Mian-Chowla sequence. Nigel Galloway: March 23rd., 2019
let mC=let rec fN i g l=seq{
Line 536 ⟶ 632:
yield b; yield! fN (l::i) (a|>List.filter(fun n->n>b)) b}
seq{yield 1; yield! fN [] [] 1}
</syntaxhighlight>
</lang>
===The Tasks===
;First 30
<langsyntaxhighlight lang="fsharp">
mC |> Seq.take 30 |> Seq.iter(printf "%d ");printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 547 ⟶ 643:
</pre>
;91 to 100
<langsyntaxhighlight lang="fsharp">
mC |> Seq.skip 90 |> Seq.take 10 |> Seq.iter(printf "%d ");printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 556 ⟶ 652:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: fry hash-sets io kernel math prettyprint sequences sets ;
 
: next ( seq sums speculative -- seq' sums' speculative' )
Line 571 ⟶ 667:
[ 30 head "First 30 terms of the Mian-Chowla sequence:" ]
[ 10 tail* "Terms 91-100 of the Mian-Chowla sequence:" ] bi
[ print [ pprint bl ] each nl nl ] 2bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 580 ⟶ 676:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">redim as uinteger mian(0 to 1)
redim as uinteger sums(0 to 2)
mian(0) = 1 : mian(1) = 2
sums(0) = 2 : sums(1) = 3 : sums(2) = 4
dim as uinteger n_mc = 2, n_sm = 3, curr = 3, tempsum
while n_mc < 101
for i as uinteger = 0 to n_mc - 1
tempsum = curr + mian(i)
for j as uinteger = 0 to n_sm - 1
if tempsum = sums(j) then goto loopend
next j
next i
redim preserve as uinteger mian(0 to n_mc)
mian(n_mc) = curr
redim preserve as uinteger sums(0 to n_sm + n_mc)
for j as uinteger = 0 to n_mc - 1
sums(n_sm + j) = mian(j) + mian(n_mc)
next j
n_mc += 1
n_sm += n_mc
sums(n_sm-1) = 2*curr
loopend:
curr += 1
wend
 
print "Mian-Chowla numbers 1 through 30: ",
for i as uinteger = 0 to 29
print mian(i),
next i
print
print "Mian-Chowla numbers 91 through 100: ",
for i as uinteger = 90 to 99
print mian(i),
next i
print</syntaxhighlight>
{{out}}
<pre>
Mian-Chowla numbers 1 through 30: 1 2 4 8 13 21 31 45
66 81 97 123 148 182 204 252 290 361 401
475 565 593 662 775 822 916 970 1016 1159 1312
 
Mian-Chowla numbers 91 through 100: 22526 23291 23564 23881 24596 24768 25631 26037 26255 27219</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 625 ⟶ 765:
fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
fmt.Println(mc[90:100])
}</langsyntaxhighlight>
 
{{out}}
Line 637 ⟶ 777:
<br>
Quicker version (runs in less than 0.02 seconds on Celeron N3050 @1.6 GHz), output as before:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 678 ⟶ 818:
fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
fmt.Println(mc[90:100])
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
{{Trans|Python}}
{{Trans|JavaScript}}
<langsyntaxhighlight lang="haskell">import Data.Set (Set, fromList, insert, member)
 
------------------- MIAN-CHOWLA SEQUENCE -----------------
mianChowlas :: Int -> [Int]
mianChowlas n =
reverse $. snd $. (iterate nextMC (fromList [2], [1]) !!) (n. -subtract 1)
 
nextMC :: (Set Int, [Int]) -> (Set Int, [Int])
nextMC (sumSet, mcs@(n:_)) =
let(foldr validinsert x = allsumSet (not(2 .* flipm) member: sumSet .fmap (xm +) mcs), m : mcs)
where
m = until valid succ n
in (foldr insertvalid sumSetx = not $ any ((2flip *member m)sumSet : fmap. (mx +) mcs), m : mcs)
m = until valid succ n
 
--------------------------- TEST -------------------------
main :: IO ()
main =
Line 703 ⟶ 846:
, "Terms 91 to 100 of the Mian-Chowla series:"
, show $ drop 90 (mianChowlas 100)
]</langsyntaxhighlight>
{{Out}}
<pre>First 30 terms of the Mian-Chowla series:
Line 713 ⟶ 856:
=={{header|J}}==
 
<syntaxhighlight lang="j">
<lang j>
NB. http://rosettacode.org/wiki/Mian-Chowla_sequence
 
Line 731 ⟶ 874:
 
prime_q =: 1&p: NB. for fun look at prime generation suitability
</syntaxhighlight>
</lang>
 
<pre>
Line 748 ⟶ 891:
0 1 0 0 0 0 0 0 0 0
</pre>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">
import java.util.Arrays;
 
Line 826 ⟶ 970:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 838 ⟶ 982:
=={{header|JavaScript}}==
{{Trans|Python}} (Functional Python version)
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
// main :: IO ()
const main = () => {
 
const genMianChowla = mianChowlas();
console.log([
'Mian-Chowla terms 1-30:',
take(30, genMianChowla),(
genMianChowla
),
 
'\nMian-Chowla terms 91-100:',
(() => {
drop(60, )(genMianChowla);,
return take(10, genMianChowla);(
})() genMianChowla
)
)
].join('\n') + '\n');
};
Line 877 ⟶ 1,025:
return true;
};
const x = until(valid,)(x succ,=> 1 + x)(n);
return [
sumList(mcs, )(x)
.reduce(
(a, n) => (a.add(n), a),
Line 886 ⟶ 1,034:
mcs.concat(x),
x
];
 
};
 
// sumList :: [Int] -> Int -> [Int]
const sumList = (xs, n) =>
// Series so far -> additional term -> new sums
n => [2 * n].concat(xs.map(x => n + x, xs));
 
 
// GENERIC FUNCTIONS ---------------- GENERIC FUNCTIONS ----------------
 
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = (n, xs) =>
xs => Infinity > length(xs) ? (
xs.slice(n)
) : (take(n, )(xs), xs);
 
 
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
 
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
(Array.isArray(xs) || 'string' === typeof xs) ? (
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
 
// succ :: Int -> Int
const succ = x => 1 + x;
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
// The first n elements of a list,
'GeneratorFunction' !== xs.constructor.constructor.name ? (
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
Line 937 ⟶ 1,080:
return x.done ? [] : [x.value];
}));
 
 
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let vf => x; => {
while (!p(v)) let v = f(v)x;
return while (!p(v)) v = f(v);
} return v;
};
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Mian-Chowla terms 1-30:
Line 953 ⟶ 1,098:
 
Mian-Chowla terms 91-100:
22526,23291,23564,23881,24596,24768,25631,26037,26255,27219</pre>
 
=={{header|jq}}==
[Finished in 0.184s]
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
# Input: a bag-of-words (bow)
# Output: either an augmented bow, or nothing if a duplicate is found
def augment_while_unique(stream):
label $out
| foreach ((stream|tostring), null) as $word (.;
if $word == null then .
elif has($word) then break $out
else .[$word] = 1
end;
select($word == null) );
 
# For speedup, store "sums" as a hash
(Executed in the Atom editor, using Run Script)</pre>
def mian_chowlas:
{m:[1], sums: {"1":1}}
| recurse(
.m as $m
| .sums as $sums
| first(range(1+$m[-1]; infinite) as $i
| $sums
| augment_while_unique( ($m[] | (.+$i)), (2*$i))
| [$i, .] ) as [$i, $sums]
| {m: ($m + [$i]), $sums} )
| .m[-1] ;</syntaxhighlight>
'''The Tasks'''
<syntaxhighlight lang="jq">[limit(100; mian_chowlas)]
| "First thirty: \(.[:30]);",
"91st through 100th: \(.[90:])."</syntaxhighlight>
{{out}}
<pre>
First thirty: [1,2,4,8,13,21,31,45,66,81,97,123,148,182,204,252,290,361,401,475,565,593,662,775,822,916,970,1016,1159,1312];
91st through 100th: [22526,23291,23564,23881,24596,24768,25631,26037,26255,27219].
</pre>
 
=={{header|Julia}}==
Optimization in Julia can be an incremental process. The first version of this program ran in over 2 seconds. Using a hash table for lookup of sums and avoiding reallocation of arrays helps considerably.
<langsyntaxhighlight lang="julia">function mianchowla(n)
seq = ones(Int, n)
sums = Dict{Int,Int}()
Line 997 ⟶ 1,175:
@time testmianchowla()
 
</langsyntaxhighlight>{{out}}
<pre>
...
Line 1,004 ⟶ 1,182:
0.007524 seconds (168 allocations: 404.031 KiB)
</pre>
 
=={{header|Kotlin}}==
 
{{trans|Go}}
===Translation of Go===
<lang scala>// Version 1.3.21
 
<syntaxhighlight lang="scala">// Version 1.3.21
 
fun mianChowla(n: Int): List<Int> {
Line 1,041 ⟶ 1,222:
println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
println(mc.subList(90, 100))
}</langsyntaxhighlight>
 
{{output}}
Line 1,051 ⟶ 1,232:
[22526, 23291, 23564, 23881, 24596, 24768, 25631, 26037, 26255, 27219]
</pre>
 
=== Idiomatic ===
 
<syntaxhighlight lang="kotlin">
fun sumsRemainDistinct(candidate: Int, seq: Iterable<Int>, sums: MutableSet<Int>): Boolean {
val candidateSums = mutableListOf<Int>()
 
for (s in seq) {
when ((candidate + s) !in sums) {
true -> candidateSums.add(candidate + s)
false -> return false
}
}
with(sums) {
addAll(candidateSums)
add(candidate + candidate)
}
return true
}
 
fun mianChowla(n: Int): List<Int> {
val bufferSeq = linkedSetOf<Int>()
val bufferSums = linkedSetOf<Int>()
 
val sequence = generateSequence(1) { it + 1 } // [1,2,3,..]
.filter { sumsRemainDistinct(it, bufferSeq, bufferSums) }
.onEach { bufferSeq.add(it) }
 
return sequence.take(n).toList()
}
 
fun main() {
mianChowla(100).also {
println("Mian-Chowla[1..30] = ${it.take(30)}")
println("Mian-Chowla[91..100] = ${it.drop(90)}")
}
}
</syntaxhighlight>
{{output}}
<pre>
Mian-Chowla[1..30] = [1, 2, 4, 8, 13, 21, 31, 45, 66, 81, 97, 123, 148, 182, 204, 252, 290,
361, 401, 475, 565, 593, 662, 775, 822, 916, 970, 1016, 1159, 1312]
 
Mian-Chowla[91..100] = [22526, 23291, 23564, 23881, 24596, 24768, 25631, 26037, 26255, 27219]
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">n = {m} = {1};
tmp = {2};
Do[
m++;
While[ContainsAny[tmp, m + n],
m++
];
tmp = Join[tmp, n + m];
AppendTo[tmp, 2 m];
AppendTo[n, m]
,
{99}
]
Row[Take[n, 30], ","]
Row[Take[n, {91, 100}], ","]</syntaxhighlight>
{{out}}
<pre>1,2,4,8,13,21,31,45,66,81,97,123,148,182,204,252,290,361,401,475,565,593,662,775,822,916,970,1016,1159,1312
22526,23291,23564,23881,24596,24768,25631,26037,26255,27219</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import intsets, strutils, times
 
proc mianchowla(n: Positive): seq[int] =
result = @[1]
var sums = [2].toIntSet()
var candidate = 1
 
while result.len < n:
# Test successive candidates.
var fit = false
result.add 0 # Make room for next value.
while not fit:
inc candidate
fit = true
result[^1] = candidate
# Check the sums.
for val in result:
if val + candidate in sums:
# Failed to satisfy criterium.
fit = false
break
# Add the new sums to the set of sums.
for val in result:
sums.incl val + candidate
 
let t0 = now()
let seq100 = mianchowla(100)
echo "The first 30 terms of the Mian-Chowla sequence are:"
echo seq100[0..29].join(" ")
echo ""
echo "Terms 91 to 100 of the sequence are:"
echo seq100[90..99].join(" ")
 
echo ""
echo "Computation time: ", (now() - t0).inMilliseconds, " ms"</syntaxhighlight>
 
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 to 100 of the sequence are:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
 
Computation time: 2 ms</pre>
 
=={{header|Pascal}}==
Line 1,085 ⟶ 1,377:
real 1932m34,698s => 1d8h12m35</pre>
<langsyntaxhighlight lang="pascal">program MianChowla;
//compiling with /usr/lib/fpc/3.2.0/ppcx64.2 -MDelphi -O4 -al "%f"
{$CODEALIGN proc=8,loop=4 }
Line 1,239 ⟶ 1,531:
writeln;
END.
</syntaxhighlight>
</lang>
{{Out}}
<pre>Allocated memory 2014024
Line 1,259 ⟶ 1,551:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,280 ⟶ 1,572:
my @mian_chowla = generate_mc(100);
say "First 30 terms in the Mian–Chowla sequence:\n", join(' ', @mian_chowla[ 0..29]),
"\nTerms 91 through 100:\n", join(' ', @mian_chowla[90..99]);</langsyntaxhighlight>
{{out}}
<pre>First 30 terms in the Mian–Chowla sequence:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 through 100:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219</pre>
 
=={{header|Perl 6}}==
<lang perl6>my @mian-chowla = 1, |(2..Inf).map: -> $test {
state $index = 1;
state %sums = 2 => 1;
my $next;
my %these;
@mian-chowla[^$index].map: { ++$next and last if %sums{$_ + $test}:exists; ++%these{$_ + $test} };
next if $next;
++%sums{$test + $test};
%sums.push: %these;
++$index;
$test
};
 
put "First 30 terms in the Mian–Chowla sequence:\n", @mian-chowla[^30];
put "\nTerms 91 through 100:\n", @mian-chowla[90..99];</lang>
{{out}}
<pre>First 30 terms in the Mian–Chowla sequence:
Line 1,312 ⟶ 1,581:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function mian_chowla(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">mian_chowla</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence mc = {1},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mc</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
is = {false,true}
<span style="color: #000000;">is</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">}</span>
integer len_is = 2, s
<span style="color: #004080;">integer</span> <span style="color: #000000;">len_is</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span>
for i=2 to n do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
sequence isx = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">isx</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer j = mc[i-1]+1
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">1</span>
mc = append(mc,j)
<span style="color: #000000;">mc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">)</span>
while true do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
for k=1 to length(mc) do
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mc</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
s = mc[k] + j
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">j</span>
if s<=len_is and is[s] then
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">len_is</span> <span style="color: #008080;">and</span> <span style="color: #000000;">is</span><span style="color: #0000FF;">[</span><span style="color: #000000;">s</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
isx = {}
<span style="color: #000000;">isx</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
isx = append(isx,s)
<span style="color: #000000;">isx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if length(isx) then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isx</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
s = isx[$]
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">isx</span><span style="color: #0000FF;">[$]</span>
if s>len_is then
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">></span><span style="color: #000000;">len_is</span> <span style="color: #008080;">then</span>
is &= repeat(false,s-len_is)
<span style="color: #000000;">is</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">len_is</span><span style="color: #0000FF;">)</span>
len_is = length(is)
<span style="color: #000000;">len_is</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">is</span><span style="color: #0000FF;">)</span>
end if
for k<span style=1"color: to#008080;">end</span> length(isx)<span style="color: do#008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isx</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
is[isx[k]] = true
<span style="color: #000000;">is</span><span style="color: #0000FF;">[</span><span style="color: #000000;">isx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
j += 1
<span style="color: #000000;">j</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
mc[i] = j
<span style="color: #000000;">mc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">j</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return mc
<span style="color: #008080;">return</span> <span style="color: #000000;">mc</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
atom t0 = time()
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
sequence mc = mian_chowla(100)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mian_chowla</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
printf(1,"The first 30 terms of the Mian-Chowla sequence are:\n %v\n",{mc[1..30]})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 30 terms of the Mian-Chowla sequence are:\n %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">30</span><span style="color: #0000FF;">]})</span>
printf(1,"Terms 91 to 100 of the Mian-Chowla sequence are:\n %v\n",{mc[91..100]})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Terms 91 to 100 of the Mian-Chowla sequence are:\n %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">91</span><span style="color: #0000FF;">..</span><span style="color: #000000;">100</span><span style="color: #0000FF;">]})</span>
printf(1,"completed in %s\n",{elapsed(time()-t0)})</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"completed in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,363 ⟶ 1,634:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">from itertools import count, islice, chain
import time
 
Line 1,392 ⟶ 1,663:
pretty("The first 30 terms", ts, 0, 30)
pretty("\nTerms 91 to 100", ts, 90, 100)
print("\nComputation time was", (time.time()-st) * 1000, "ms")</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 1,404 ⟶ 1,675:
===Functional===
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Mian-Chowla series'''
 
from itertools import (islice)
Line 1,511 ⟶ 1,782:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First 30 terms of the Mian-Chowla series:
Line 1,520 ⟶ 1,791:
 
(Computation time c. 27 ms)</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ stack ] is makeable ( --> s )
 
[ temp put
1 bit makeable put
' [ 1 ] 1
[ true temp put
1+
over witheach
[ over + bit
makeable share & if
[ false temp replace
conclude ] ]
temp take if
[ dup dip join
over witheach
[ over + bit
makeable take
| makeable put ] ]
over size temp share = until ]
makeable release
temp release
drop ] is mian-chowla ( n --> [ )
 
100 mian-chowla
30 split swap echo cr
-10 split nip echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312 ]
[ 22526 23291 23564 23881 24596 24768 25631 26037 26255 27219 ]
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my @mian-chowla = 1, |(2..Inf).map: -> $test {
state $index = 1;
state %sums = 2 => 1;
my $next;
my %these;
@mian-chowla[^$index].map: { ++$next and last if %sums{$_ + $test}:exists; ++%these{$_ + $test} };
next if $next;
++%sums{$test + $test};
%sums.push: %these;
++$index;
$test
};
 
put "First 30 terms in the Mian–Chowla sequence:\n", @mian-chowla[^30];
put "\nTerms 91 through 100:\n", @mian-chowla[90..99];</syntaxhighlight>
{{out}}
<pre>First 30 terms in the Mian–Chowla sequence:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 through 100:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219</pre>
 
=={{header|REXX}}==
Line 1,527 ⟶ 1,857:
do j=i to t; ···
but the 1<sup>st</sup> version is faster.
<langsyntaxhighlight lang="rexx">/*REXX program computes and displays any range of the Mian─Chowla integer sequence.*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
Line 1,543 ⟶ 1,873:
end /*i*/
#= # + 1 /*bump the counter of terms in the list*/
if #>=LO &then if #<=HI then $= $ t /*In the specified range? Add to list.*/
end /*t*/
/*stick a fork in it, we're all done. */
say 'The Mian─Chowla sequence for terms ' LO "──►" HI ' (inclusive):'
say strip($) /*ignore the leading superfluous blank.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,561 ⟶ 1,891:
=={{header|Ruby}}==
{{trans|Go}}
<langsyntaxhighlight lang="ruby">require 'set'
n, ts, mc, sums = 100, [], [1], Set.new
sums << 2
Line 1,585 ⟶ 1,915:
puts "The first 30 terms#{s}#{mc.slice(0..29).join(' ')}\n\n"
puts "Terms 91 to 100#{s}#{mc.slice(90..99).join(' ')}\n\n"
puts "Computation time was #{et.round(1)}ms."</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 1,597 ⟶ 1,927:
Or using an Enumerator:
 
<langsyntaxhighlight lang="ruby">mian_chowla = Enumerator.new do |yielder|
mc, sums = [1], {}
1.step do |n|
Line 1,615 ⟶ 1,945:
puts "The first 30 terms#{s}#{res[0,30].join(' ')}\n
Terms 91 to 100#{s}#{res[90,10].join(' ')}"
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Go}}
<langsyntaxhighlight lang="ruby">var (n, sums, ts, mc) = (100, Set([2]), [], [1])
var st = Time.micro_secmicro
for i in (1 ..^ n) {
for j in (mc[i-1]+1 .. Inf) {
Line 1,626 ⟶ 1,956:
for k in (0 .. i) {
var sum = mc[k]+j
if (sums.existshas(sum)) {
ts.clear
break
Line 1,633 ⟶ 1,963:
}
if (ts.len > 0) {
sums |= (sums|Set(ts...))
break
}
}
}
var et = (Time.micro_secmicro - st)
var s = " of the Mian-Chowla sequence are:\n"
say "The first 30 terms#{s}#{mc.ftfirst(0, 2930).join(' ')}\n"
say "Terms 91 to 100#{s}#{mc.ftslice(90, 99).first(10).join(' ')}\n"
say "Computation time was #{et} seconds."</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 1,650 ⟶ 1,980:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
 
Computation time was 32.98316288 seconds.</pre>
 
=={{header|Swift}}==
Line 1,656 ⟶ 1,986:
{{trans|Go}}
 
<langsyntaxhighlight Swiftlang="swift">public func mianChowla(n: Int) -> [Int] {
var mc = Array(repeating: 0, count: n)
var ls = [2: true]
Line 1,694 ⟶ 2,024:
 
print("First 30 terms in sequence are: \(Array(seq.prefix(30)))")
print("Terms 91 to 100 are: \(Array(seq[90..<100]))")</langsyntaxhighlight>
 
{{out}}
Line 1,702 ⟶ 2,032:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Mian-Chowla sequence - VBScript - 15/03/2019
Const m = 100, mm=28000
ReDim r(mm), v(mm * 2)
Line 1,746 ⟶ 2,076:
wscript.echo "The Mian-Chowla sequence for elements 91 to 100:"
wscript.echo s2
wscript.echo "Computation time: "& Int(Timer-t0) &" sec"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,759 ⟶ 2,089:
'''Shorter execution time'''
{{trans|Go}}
<langsyntaxhighlight lang="vb">' Mian-Chowla sequence - VBScript - March 19th, 2019
 
Function Find(x(), val) ' finds val on a pre-sorted list
Line 1,801 ⟶ 2,131:
If i < 30 or i >= 90 Then wscript.stdout.write(mc(i) & " ")
Next
wscript.echo vblf & vbLf & "Computation time: "& Timer - st &" seconds."</langsyntaxhighlight>
{{out}}
''Hint:'' save the code to a .vbs file (such as "mc.vbs") and start it with this command Line: "cscript.exe /nologo mc.vbs". This will send the output to the console instead of a series of message boxes.<br/>This goes faster because the cache of sums is maintained throughout the computation instead of being reinitialized at each iteration. Also the ''sums()'' array is kept sorted to find any previous values quicker.
Line 1,814 ⟶ 2,144:
=={{header|Visual Basic .NET}}==
{{trans|Go}}
<langsyntaxhighlight lang="vbnet">Module Module1
Function MianChowla(ByVal n As Integer) As Integer()
Dim mc(n - 1) As Integer, sums, ts As New HashSet(Of Integer),
Line 1,840 ⟶ 2,170:
String.Join(" ", mc.Take(30)), String.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds)
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>The first 30 terms of the Mian-Chowla sequence are:
Line 1,849 ⟶ 2,179:
 
Computation time was 18ms.</pre>
 
=={{header|Wren}}==
{{trans|C#}}
<syntaxhighlight lang="wrent">var mianChowla = Fn.new { |n|
var mc = List.filled(n, 0)
var sums = {}
var ts = {}
mc[0] = 1
sums[2] = true
for (i in 1...n) {
var j = mc[i-1] + 1
while (true) {
mc[i] = j
for (k in 0..i) {
var sum = mc[k] + j
if (sums[sum]) {
ts.clear()
break
}
ts[sum] = true
}
if (ts.count > 0) {
for (key in ts.keys) sums[key] = true
break
}
j = j + 1
}
}
return mc
}
 
var start = System.clock
var mc = mianChowla.call(100)
System.print("The first 30 terms of the Mian-Chowla sequence are:\n%(mc[0..29].join(" "))")
System.print("\nTerms 91 to 100 of the Mian-Chowla sequence are:\n%(mc[90..99].join(" "))")
System.print("\nTook %(((System.clock - start)*1000).round) milliseconds")</syntaxhighlight>
 
{{out}}
<pre>
The first 30 terms of the Mian-Chowla sequence are:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 to 100 of the Mian-Chowla sequence are:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
 
Took 32 milliseconds
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
Takes about 1.5 seconds on RPi-4.
<syntaxhighlight lang "XPL0">define N = 100;
define NN = (N * (N+1)) >> 1;
 
func Contains(Lst, Item, Size);
int Lst, Item, Size, I;
[for I:= Size-1 downto 0 do
if Item = Lst(I) then return true;
return false;
];
int MC(N);
 
proc MianChowla;
int Sums(NN), Sum, LE, SS, I, J, K;
[MC(0):= 1;
Sums(0):= 2;
SS:= 1;
for I:= 1 to N-1 do
[LE:= SS;
J:= MC(I-1) + 1;
MC(I):= J;
K:= 0;
loop [Sum:= MC(K) + J;
if Contains(Sums, Sum, SS) then
[SS:= LE;
J:= J+1;
MC(I):= J;
K:= 0;
]
else
[Sums(SS):= Sum;
SS:= SS+1;
K:= K+1;
if K > I then quit;
];
];
];
];
int I;
[MianChowla;
Text(0, "The first 30 terms of the Mian-Chowla sequence are:^m^j");
for I:= 0 to 30-1 do
[IntOut(0, MC(I)); ChOut(0, ^ )];
Text(0, "^m^j^m^jTerms 91 to 100 of the Mian-Chowla sequence are:^m^j");
for I:= 90 to 100-1 do
[IntOut(0, MC(I)); ChOut(0, ^ )];
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
The first 30 terms of the Mian-Chowla sequence are:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312
 
Terms 91 to 100 of the Mian-Chowla sequence are:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
</pre>
9,476

edits