Data update

This commit is contained in:
Ingy döt Net 2023-07-01 19:04:33 -04:00
parent 8f05c7136f
commit 0bf4da02c3
82 changed files with 2194 additions and 118 deletions

View File

@ -0,0 +1 @@
../../Task/Dragon-curve/ANSI-BASIC

1
Lang/ARM-Assembly/K-d-tree Symbolic link
View File

@ -0,0 +1 @@
../../Task/K-d-tree/ARM-Assembly

1
Lang/BASIC/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/BASIC

1
Lang/BCPL/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/BCPL

1
Lang/CLU/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/CLU

1
Lang/COBOL/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/COBOL

View File

@ -0,0 +1 @@
../../Task/Totient-function/Cowgol

View File

@ -0,0 +1 @@
../../Task/Factorial-primes/Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Lucas-Lehmer-test/Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Prime-decomposition/Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Ultra-useful-primes/Craft-Basic

1
Lang/Draco/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/Draco

View File

@ -0,0 +1 @@
../../Task/OpenWebNet-password/FreeBASIC

View File

@ -0,0 +1 @@
../../Task/Erd-s-Nicolas-numbers/FutureBasic

View File

@ -0,0 +1 @@
../../Task/Mertens-function/FutureBasic

1
Lang/Java/Babylonian-spiral Symbolic link
View File

@ -0,0 +1 @@
../../Task/Babylonian-spiral/Java

View File

@ -0,0 +1 @@
../../Task/Bioinformatics-Global-alignment/Java

1
Lang/Kotlin/Bifid-cipher Symbolic link
View File

@ -0,0 +1 @@
../../Task/Bifid-cipher/Kotlin

1
Lang/MAD/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/MAD

View File

@ -0,0 +1 @@
../../Task/Totient-function/Miranda

View File

@ -0,0 +1 @@
../../Task/Totient-function/Modula-2

1
Lang/Oberon/Tau-number Symbolic link
View File

@ -0,0 +1 @@
../../Task/Tau-number/Oberon

1
Lang/PL-I/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/PL-I

1
Lang/PL-M/Totient-function Symbolic link
View File

@ -0,0 +1 @@
../../Task/Totient-function/PL-M

View File

@ -0,0 +1 @@
../../Task/Ultra-useful-primes/Python

1
Lang/Ruby/Achilles-numbers Symbolic link
View File

@ -0,0 +1 @@
../../Task/Achilles-numbers/Ruby

View File

@ -0,0 +1 @@
../../Task/Babbage-problem/Tiny-Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Tau-number/Tiny-Craft-Basic

View File

@ -0,0 +1 @@
../../Task/Simple-turtle-graphics/XPL0

View File

@ -11,18 +11,18 @@ pub fn main() !void {
{
const nc = try getCombs(allocator, 1, 7, true);
defer allocator.free(nc.combinations);
_ = try stdout.print("{d} unique solutions in 1 to 7\n", .{nc.num});
_ = try stdout.print("{any}\n", .{nc.combinations});
try stdout.print("{d} unique solutions in 1 to 7\n", .{nc.num});
try stdout.print("{any}\n", .{nc.combinations});
}
{
const nc = try getCombs(allocator, 3, 9, true);
defer allocator.free(nc.combinations);
_ = try stdout.print("{d} unique solutions in 3 to 9\n", .{nc.num});
_ = try stdout.print("{any}\n", .{nc.combinations});
try stdout.print("{d} unique solutions in 3 to 9\n", .{nc.num});
try stdout.print("{any}\n", .{nc.combinations});
}
{
const nc = try getCombs(allocator, 0, 9, false);
defer allocator.free(nc.combinations);
_ = try stdout.print("{d} non-unique solutions in 0 to 9\n", .{nc.num});
try stdout.print("{d} non-unique solutions in 0 to 9\n", .{nc.num});
}
}

View File

@ -0,0 +1,23 @@
require 'prime'
def achilles?(n)
exponents = n.prime_division.map(&:last)
exponents.none?(1) && exponents.inject(&:gcd) == 1
end
def 𝜑(n)
n.prime_division.inject(1){|res, (pr, exp)| res * (pr-1) * pr**(exp-1) }
end
achilleses = (2..).lazy.select{|n| achilles?(n) }
n = 50
puts "First #{n} Achilles numbers:"
achilleses.first(n).each_slice(10){|s| puts "%9d"*s.size % s}
puts "\nFirst #{n} strong Achilles numbers:"
achilleses.select{|ach| achilles?(𝜑(ach)) }.first(n).each_slice(10){|s| puts "%9d"*s.size % s }
puts
counts = achilleses.take_while{|ach| ach < 1000000}.map{|a| a.digits.size }.tally
counts.each{|k, v| puts "#{k} digits: #{v}" }

View File

@ -1,5 +1,5 @@
bgcolor 0, 0, 0
cls
cls graphics
fgcolor 255, 255, 0
define pi = 3.14, size = 80
@ -13,5 +13,3 @@ for t = 0 to size * pi step .1
wait
next t
end

View File

@ -0,0 +1,12 @@
10 print "calculating..."
20 let n = 2
30 rem do
40 let n = n + 2
50 if (n ^ 2) % 1000000 <> 269696 then 30
60 print "The smallest number whose square ends in 269696 is: ", n
70 print "It's square is ", n * n

View File

@ -0,0 +1,88 @@
import java.awt.Point;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public final class BabylonianSpiral {
public static void main(String[] aArgs) throws IOException {
List<Point> points = babylonianSpiral(10_000);
System.out.println("The first 40 points of the Babylonian spiral are:");
for ( int i = 0, column = 0; i < 40; i++ ) {
System.out.print(String.format("%9s%s",
"(" + points.get(i).x + ", " + points.get(i).y + ")", ( ++column % 10 == 0 ) ? "\n" : " "));
}
System.out.println();
String text = svgText(points, 800);
Files.write(Paths.get("BabylonianSpiralJava.svg"), text.getBytes());
}
private static List<Point> babylonianSpiral(int aStepCount) {
List<Integer> squares = IntStream.rangeClosed(0, aStepCount).map( i -> i * i ).boxed().toList();
List<Point> deltas = Stream.of( new Point(0, 0), new Point(0, 1) ).collect(Collectors.toList());
long norm = 1;
for ( int step = 0; step < aStepCount - 2; step++ ) {
Point previousPoint = deltas.get(deltas.size() - 1);
final double theta = Math.atan2(previousPoint.y, previousPoint.x);
Set<Point> candidates = new HashSet<Point>();
while ( candidates.isEmpty() ) {
norm += 1;
for ( int i = 0; i < aStepCount; i++ ) {
long a = squares.get(i);
if ( a > norm / 2 ) {
break;
}
for ( int j = (int) Math.sqrt(norm) + 1; j >= 0; j-- ) {
long b = squares.get(j);
if ( a + b < norm ) {
break;
}
if ( a + b == norm ) {
candidates.addAll(
List.of( new Point(i, j), new Point(-i, j), new Point(i, -j), new Point(-i, -j),
new Point(j, i), new Point(-j, i), new Point(j, -i), new Point(-j, -i) ));
}
}
}
}
Comparator<Point> comparatorPoint = (one, two) -> Double.compare(
( theta - Math.atan2(one.y, one.x) + TAU ) % TAU, ( theta - Math.atan2(two.y, two.x) + TAU ) % TAU);
Point minimum = candidates.stream().min(comparatorPoint).get();
deltas.add(minimum);
}
for ( int i = 0; i < deltas.size() - 1; i++ ) {
deltas.set(i + 1, new Point(deltas.get(i).x + deltas.get(i + 1).x, deltas.get(i).y + deltas.get(i + 1).y));
}
return deltas;
}
private static String svgText(List<Point> aPoints, int aSize) {
StringBuilder text = new StringBuilder();
text.append("<svg xmlns='http://www.w3.org/2000/svg'");
text.append(" width='" + aSize + "' height='" + aSize + "'>\n");
text.append("<rect width='100%' height='100%' fill='cyan'/>\n");
text.append("<path stroke-width='1' stroke='black' fill='cyan' d='");
for ( int i = 0; i < aPoints.size(); i++ ) {
text.append(( i == 0 ? "M" : "L" ) +
( 150 + aPoints.get(i).x / 20 ) + ", " + ( 525 - aPoints.get(i).y / 20 ) + " ");
}
text.append("'/>\n</svg>\n");
return text.toString();
}
private static final double TAU = 2 * Math.PI;
}

View File

@ -0,0 +1,77 @@
import kotlin.math.sqrt
data class Square(private val square: String) {
private val dim: Int =
sqrt(square.length.toDouble()).toInt()
fun encode(ch: Char): Pair<Int, Int> =
square.indexOf(ch).let { idx -> Pair(idx / dim, idx.mod(dim)) }
fun decode(pair: List<Int>): Char =
square[pair[0] * dim + pair[1]]
fun decode(row: Int, col: Int): Char =
square[row * dim + col]
}
class Bifid(private val square: Square) {
fun encrypt(str: String): String {
fun expandAndScatter(str: String): IntArray {
val buffer = IntArray(str.length * 2)
str.forEachIndexed { i, ch ->
with(square.encode(ch)) {
buffer[i] = first
buffer[str.length + i] = second
}
}
return buffer
}
val buffer = expandAndScatter(str)
val characters: List<Char> = buffer.asIterable()
.windowed(size = 2, step = 2)
.map { square.decode(it) }
return String(characters.toCharArray())
}
fun decrypt(str: String): String {
fun expand(str: String): IntArray {
val buffer = IntArray(str.length * 2)
for (i in buffer.indices step 2) {
with(square.encode(str[i / 2])) {
buffer[i] = first
buffer[1 + i] = second
}
}
return buffer
}
val buffer = expand(str)
val characters = str.toCharArray()
for (i in characters.indices) {
characters[i] = square.decode(buffer[i], buffer[characters.size + i])
}
return String(characters)
}
}
fun main() {
with (Bifid(Square("ABCDEFGHIKLMNOPQRSTUVWXYZ"))) {
println("\n### ABC... 5x5")
encrypt("ATTACKATDAWN").also { println("ATTACKATDAWN -> $it") }
decrypt("DQBDAXDQPDQH").also { println("DQBDAXDQPDQH -> $it") }
}
with(Bifid(Square("BGWKZQPNDSIOAXEFCLUMTHYVR"))) {
println("\n### BGW... 5x5")
encrypt("FLEEATONCE").also { println("FLEEATONCE -> $it") }
decrypt("UAEOLWRINS").also { println("UAEOLWRINS -> $it") }
encrypt("ATTACKATDAWN").also { println("ATTACKATDAWN -> $it") }
decrypt("EYFENGIWDILA").also { println("EYFENGIWDILA -> $it") }
}
with(Bifid(Square("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))) {
println("\n### ABC... 6x6")
encrypt("THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY").also { println("$it") }
decrypt("TBPDIPHJSPOTAIVMGPCZKNSCN09BFIHK64I7BM4").also { println("$it") }
}
}

View File

@ -0,0 +1,128 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public final class BioinformaticsGlobalAlignment {
public static void main(String[] aArgs) {
List<List<String>> testSequences = Arrays.asList(
Arrays.asList( "TA", "AAG", "TA", "GAA", "TA" ),
Arrays.asList( "CATTAGGG", "ATTAG", "GGG", "TA" ),
Arrays.asList( "AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA" ),
Arrays.asList( "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT",
"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT",
"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT",
"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC",
"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT",
"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC",
"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT",
"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA" )
);
for ( List<String> test : testSequences ) {
for ( String superstring : shortestCommonSuperstrings(test) ) {
printReport(superstring);
}
}
}
// Return a set containing all of the shortest common superstrings of the given list of strings.
private static Set<String> shortestCommonSuperstrings(List<String> aList) {
List<String> deduplicated = deduplicate(aList);
Set<String> shortest = new HashSet<String>();
shortest.add(String.join("", deduplicated));
int shortestLength = aList.stream().mapToInt( s -> s.length() ).sum();
for ( List<String> permutation : permutations(deduplicated) ) {
String candidate = permutation.stream().reduce("", (a, b) -> concatenate(a, b) );
if ( candidate.length() < shortestLength ) {
shortest.clear();
shortest.add(candidate);
shortestLength = candidate.length();
} else if ( candidate.length() == shortestLength ) {
shortest.add(candidate);
}
}
return shortest;
}
// Remove duplicate words and words which are substrings of other words in the given list.
private static List<String> deduplicate(List<String> aList) {
List<String> unique = aList.stream().distinct().collect(Collectors.toList());
List<String> result = new ArrayList<String>(unique);
List<String> markedForRemoval = new ArrayList<String>();
for ( String testWord : result ) {
for ( String word : unique ) {
if ( ! word.equals(testWord) && word.contains(testWord) ) {
markedForRemoval.add(testWord);
}
}
}
result.removeAll(markedForRemoval);
return result;
}
// Return aBefore concatenated with aAfter, removing the longest suffix of aBefore that matches a prefix of aAfter.
private static String concatenate(String aBefore, String aAfter) {
for ( int i = 0; i < aBefore.length(); i++ ) {
if ( aAfter.startsWith(aBefore.substring(i, aBefore.length())) ) {
return aBefore.substring(0, i) + aAfter;
}
}
return aBefore + aAfter;
}
// Return all permutations of the given list of strings.
private static List<List<String>> permutations(List<String> aList) {
int[] indexes = new int[aList.size()];
List<List<String>> result = new ArrayList<List<String>>();
result.add( new ArrayList<String>(aList) );
int i = 0;
while ( i < aList.size() ) {
if ( indexes[i] < i ) {
final int j = ( i % 2 == 0 ) ? 0 : indexes[i];
String temp = aList.get(j);
aList.set(j, aList.get(i));
aList.set(i, temp);
result.add( new ArrayList<String>(aList) );
indexes[i]++;
i = 0;
} else {
indexes[i] = 0;
i++;
}
}
return result;
}
// Print a report of the given string to the standard output device.
private static void printReport(String aText) {
char[] nucleotides = new char[] {'A', 'C', 'G', 'T' };
Map<Character, Integer> bases = new HashMap<Character, Integer>();
for ( char base : nucleotides ) {
bases.put(base, 0);
}
for ( char ch : aText.toCharArray() ) {
bases.merge(ch, 1, Integer::sum);
}
final int total = bases.values().stream().reduce(0, Integer::sum);
System.out.print("Nucleotide counts for: " + ( ( aText.length() > 50 ) ? System.lineSeparator() : "") );
System.out.println(aText);
System.out.print(String.format("%s%d%s%d%s%d%s%d",
"Bases: A: ", bases.get('A'), ", C: ", bases.get('C'), ", G: ", bases.get('G'), ", T: ", bases.get('T')));
System.out.println(", total: " + total + System.lineSeparator());
}
}

View File

@ -1,15 +1,17 @@
integer fn
(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span>
-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)
<span style="color: #000080;font-style:italic;">-- In the current working directory</span>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"mkdir docs"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"output.txt"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"w"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
if fn=-1 then
puts(1,"unable to create \\output.txt\n")
else
close(fn)
end if
<span style="color: #000080;font-style:italic;">-- In the filesystem root</span>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"mkdir \\docs"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"\\output.txt"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"w"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"unable to create \\output.txt\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--

View File

@ -21,18 +21,18 @@ fn ImageData() type {
}
/// Write PGM P2 ASCII to 'writer'
pub fn print(self: *const Self, writer: anytype, optional_comments: ?[]const []const u8) !void {
_ = try writer.print("P2\n", .{});
try writer.print("P2\n", .{});
if (optional_comments) |lines| {
for (lines) |line|
_ = try writer.print("# {s}\n", .{line});
try writer.print("# {s}\n", .{line});
}
_ = try writer.print("{d} {d}\n{d}\n", .{ self.w, self.h, 255 });
try writer.print("{d} {d}\n{d}\n", .{ self.w, self.h, 255 });
for (self.image, 0..) |pixel, i| {
const sep = if (i % self.w == self.w - 1) "\n" else " ";
_ = try writer.print("{d}{s}", .{ pixel.w, sep });
try writer.print("{d}{s}", .{ pixel.w, sep });
}
}
};

View File

@ -1,14 +1,14 @@
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
_ = try stdout.writeAll("Police Sanitation Fire\n");
_ = try stdout.writeAll("------ ---------- ----\n");
try stdout.writeAll("Police Sanitation Fire\n");
try stdout.writeAll("------ ---------- ----\n");
var p: usize = 2;
while (p <= 7) : (p += 2)
for (1..7 + 1) |s|
for (1..7 + 1) |f|
if (p != s and s != f and f != p and p + f + s == 12) {
_ = try stdout.print(" {d} {d} {d}\n", .{ p, s, f });
try stdout.print(" {d} {d} {d}\n", .{ p, s, f });
};
}

View File

@ -1,12 +1,12 @@
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
_ = try stdout.writeAll("Police Sanitation Fire\n");
_ = try stdout.writeAll("------ ---------- ----\n");
try stdout.writeAll("Police Sanitation Fire\n");
try stdout.writeAll("------ ---------- ----\n");
var it = SolutionIterator{};
while (it.next()) |solution| {
_ = try stdout.print(
try stdout.print(
" {d} {d} {d}\n",
.{ solution.police, solution.sanitation, solution.fire },
);

View File

@ -0,0 +1,35 @@
100 PROGRAM DragonCurve
110 DECLARE SUB Dragon
120 SET WINDOW 0, 639, 0, 399
130 SET AREA COLOR 1
140 SET COLOR MIX(1) 0, 0, 0
150 REM SIN, COS in arrays for PI/4 multipl.
160 DIM S(0 TO 7), C(0 TO 7)
170 LET QPI = PI / 4
180 FOR I = 0 TO 7
190 LET S(I) = SIN(I * QPI)
200 LET C(I) = COS(I * QPI)
210 NEXT I
220 REM ** Initialize variables non-local for SUB Dragon.
230 LET SQ = SQR(2)
240 LET X = 224
250 LET Y = 140
260 LET RotQPi = 0
270 CALL Dragon(256, 15, 1) ! Insize = 2^WHOLE_NUM (looks better)
280 REM ** Subprogram
290 SUB Dragon (Insize, Level, RQ)
300 IF Level <= 1 THEN
310 LET XN = C(RotQPi) * Insize + X
320 LET YN = S(RotQPi) * Insize + Y
330 PLOT LINES: X, 399 - Y; XN, 399 - YN
340 LET X = XN
350 LET Y = YN
360 ELSE
370 LET RotQPi = MOD((RotQPi + RQ), 8)
380 CALL Dragon(Insize / SQ, Level - 1, 1)
390 LET RotQPi = MOD((RotQPi - RQ * 2), 8)
400 CALL Dragon(Insize / SQ, Level - 1, -1)
410 LET RotQPi = MOD((RotQPi + RQ), 8)
420 END IF
430 END SUB
440 END

View File

@ -0,0 +1,24 @@
_limit = 500000
void local fn ErdosNicolasNumbers
long i, j, sum( _limit ), count( _limit )
for i = 0 to _limit
sum(i) = 1
count(i) = 1
next
for i = 2 to _limit
j = i + i
while ( j <= _limit )
if sum(j) == j then printf @"%8ld == sum of its first %3ld divisors", j, count(j)
sum(j) = sum(j) + i
count(j) = count(j) + 1
j = j + i
wend
next
end fn
fn ErdosNicolasNumbers
HandleEvents

View File

@ -2,7 +2,7 @@ define size = 16, em = 0
dim list[size]
let list[0] = 2
print 2
print 2, " ",
for i = 1 to 15
@ -14,16 +14,16 @@ for i = 1 to 15
for j = 0 to i - 1
let em = ( em * list[j] ) % k
let em = (em * list[j]) % k
next j
let em = ( em + 1 ) % k
let em = (em + 1) % k
if em = 0 then
let list[i] = k
print list[i]
print list[i], " ",
break
endif
@ -35,7 +35,3 @@ for i = 1 to 15
loop
next i
print "done."
end

View File

@ -0,0 +1,29 @@
define found = 0, fct = 0, i = 1
do
if found < 10 then
let fct = factorial(i)
if prime(fct - 1) then
let found = found + 1
print found, ": ", i, "! - 1 = ", fct - 1
endif
if prime(fct + 1) then
let found = found + 1
print found, ": ", i, "! + 1 = ", fct + 1
endif
let i = i + 1
endif
wait
loop found < 10

View File

@ -1,38 +1,40 @@
string ts1 = """
this
"string"\thing"""
(phixonline)-->
<span style="color: #004080;">string</span> <span style="color: #000000;">ts1</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
this
"string"\thing"""</span>
string ts2 = """this
"string"\thing"""
<span style="color: #004080;">string</span> <span style="color: #000000;">ts2</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""this
"string"\thing"""</span>
string ts3 = """
_____________this
"string"\thing"""
<span style="color: #004080;">string</span> <span style="color: #000000;">ts3</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
_____________this
"string"\thing"""</span>
string ts4 = `
this
"string"\thing`
<span style="color: #004080;">string</span> <span style="color: #000000;">ts4</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
this
"string"\thing`</span>
string ts5 = `this
"string"\thing`
<span style="color: #004080;">string</span> <span style="color: #000000;">ts5</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`this
"string"\thing`</span>
string ts6 = `
_____________this
"string"\thing`
<span style="color: #004080;">string</span> <span style="color: #000000;">ts6</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
_____________this
"string"\thing`</span>
string ts7 = "this\n\"string\"\\thing"
<span style="color: #004080;">string</span> <span style="color: #000000;">ts7</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"this\n\"string\"\\thing"</span>
constant tests={ts1,ts2,ts3,ts4,ts5,ts6,ts7}
for i=1 to length(tests) do
for j=1 to length(tests) do
if tests[i]!=tests[j] then crash("error") end if
end for
end for
printf(1,"""
____________Everything
(all %d tests)
works
just
file.""",length(tests))
printf(1,"""`""")
printf(1,`"""`)
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">={</span><span style="color: #000000;">ts1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts7</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</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;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</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;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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;">"""
____________Everything
(all %d tests)
works
just
file."""</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">))</span>
<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;">"""`"""</span><span style="color: #0000FF;">)</span>
<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;">`"""`</span><span style="color: #0000FF;">)</span>
<!--

View File

@ -24,4 +24,3 @@ You do not have to implement these.
The requirement for this task is specifically the nearest single neighbor.
Also there are algorithms for inserting, deleting, and balancing k-d trees.
These are also not required for the task.

View File

@ -0,0 +1,690 @@
/* ARM assembly Raspberry PI */
/* program kdtree.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* REMARK 2 : In order not to use floating point numbers,
the coordinates of the points are integers numbers.
The displayed distance represents the square of the distance between 2 points */
/* This program draws heavily from the published C program. Thanks to its creator. */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 3
.equ NBPOINTSRAND, 2000
.equ MAXCOORD, 10000
.include "../../ficmacros32.inc"
/***********************************************/
/* structures */
/**********************************************/
/* Définition node */
.struct 0
nodeKD_val: // value array
.struct nodeKD_val + (4 * MAXI)
nodeKD_left: // left pointer
.struct nodeKD_left + 4
nodeKD_right: // right pointer
.struct nodeKD_right + 4
nodeKD_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessAddressTree: .asciz "Node address : "
szMessTreeValue: .asciz " Value : "
szMessLeft: .asciz " Left : "
szMessRight: .asciz "Right : "
szMessResult: .asciz "Nearest point = "
szMessRandCoor: .asciz "\n\nRandom point coordonnés = "
szMessVisited: .asciz "Node visited = "
szMessDistance: .asciz "square distance :"
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
.align 4
tabPoint1: .int 2,3, 5,4, 9,6, 4,7, 8,1, 7,2
//tabPoint1: .int 1,7, 3,4, 4,6, 6,2, 8,12, 10,9, 12,3, 14,1
//tabPoint1: .int 3,5, 1,3, 2,8, 4,6, 5,4
.equ NBPOINTS, (. - tabPoint1) / 4
tabPoint2: .int 9,2
//tabPoint2: .int 3,7
.equ NBPOINTS2, (. - tabPoint2) / 4
iGraine: .int 123456 // random init
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
stNode1: .skip nodeKD_end
KDtree1: .skip nodeKD_end * NBPOINTS
KDtree2: .skip nodeKD_end * NBPOINTS2
KdtreeRand: .skip nodeKD_end * NBPOINTSRAND
tabPointsRand: .skip nodeKD_end
sZoneConv: .skip 24 // conversion buffer
sZoneConv1: .skip 24 // conversion buffer
sBufferConv16: .skip 16
iDistance: .skip 4 // best distance
stNearest: .skip nodeKD_end // best node
nbNodeVi: .skip 4 // visited node
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrtabPoint1 @ points array address
ldr r1,iAdrKDtree1 @ KD tree address
mov r2,#NBPOINTS @ array points size
mov r3,#2 @ domension 2
bl initKDTree @ init tree
ldr r0,iAdrKDtree1 @ KD tree address
mov r1,#0 @ start index
mov r2,#NBPOINTS / 2 @ end = array points size
mov r3,#0 @ level
mov r4,#2 @ dimension 2
bl createTree
mov r8,r0 @ save median
cmp r0,#-1
beq 100f
ldr r0,iAdrKDtree1 @ KD tree address
mov r1,#2 @ dimension 2
bl displayTree
ldr r0,iAdrtabPoint2 @ points array address
ldr r1,iAdrKDtree2 @ search KDtree address
mov r2,#NBPOINTS2 @ search array points size
mov r3,#2 @ dimension 2
bl initKDTree @ init search tree
ldr r0,iAdrKDtree1 @ KDtree address
mov r1,#nodeKD_end
mla r0,r8,r1,r0 @ compute median address
ldr r1,iAdrKDtree2 @ search KDtree address
mov r2,#0 @ first index
mov r3,#2 @ dimension 2
bl searchNearest @ search nearest point
ldr r0,iAdrszMessResult @ display résult
bl affichageMess
ldr r0,iAdrstNearest @ nearest point address
ldr r0,[r0]
mov r1,#2
bl displayCoord @ coordonnés display
ldr r0,iAdrnbNodeVi @ visited nodes
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#3
ldr r1,iAdrszMessVisited
ldr r2,iAdrsZoneConv
ldr r3,iAdrszCarriageReturn
bl displayStrings
ldr r0,iAdriDistance @ best distance address
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#3
ldr r1,iAdrszMessDistance
ldr r2,iAdrsZoneConv
ldr r3,iAdrszCarriageReturn
bl displayStrings
bl traitRandom
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessDistance: .int szMessDistance
iAdrszMessResult: .int szMessResult
iAdrszMessVisited: .int szMessVisited
iAdrszMessStart: .int szMessStart
iAdrtabPoint1: .int tabPoint1
iAdrtabPoint2: .int tabPoint2
iAdrKDtree1: .int KDtree1
iAdrKDtree2: .int KDtree2
/***************************************************/
/* traitement random points */
/***************************************************/
/* r0 array tree address */
/* r2 points number */
/* r3 dimension */
traitRandom:
push {r1-r10,lr} @ save des registres
ldr r8,iAdrKdtreeRand @ KD tree address
mov r7,#nodeKD_end
ldr r10,iNbPointsRand
mov r3,#0
1: @ loop generate random coordonnes
mov r0,#MAXCOORD
bl genereraleas @ X
mov r4,r0
mov r0,#MAXCOORD
bl genereraleas @ Y
mov r5,r0
mov r0,#MAXCOORD
bl genereraleas @ Z
mov r6,r0
mla r0,r3,r7,r8
add r1,r0,#nodeKD_val @ node address
str r4,[r1] @ store X,Y,Z
str r5,[r1,#4]
str r6,[r1,#8]
mov r4,#-1 @ init pointer left and right
str r4,[r0,#nodeKD_left]
str r4,[r0,#nodeKD_right]
add r3,r3,#1
cmp r3,r10
blt 1b
mov r0,r8 @ KD tree address
mov r1,#0 @ start indice
mov r2,r10 @ array points size
mov r3,#0 @ level
mov r4,#3 @ dimension 2
bl createTree
mov r9,r0 @ save median
@ create random search point
mov r0,#MAXCOORD
bl genereraleas
mov r4,r0
mov r0,#MAXCOORD
bl genereraleas
mov r5,r0
mov r0,#MAXCOORD
bl genereraleas
mov r6,r0
ldr r3,iAdrtabPointsRand
add r0,r3,#nodeKD_val
str r4,[r0]
str r5,[r0,#4]
str r6,[r0,#8]
ldr r0,iAdrszMessRandCoor
bl affichageMess
mov r0,r3
mov r1,#3
bl displayCoord @ search
ldr r0,iAdriDistance @ init best distance address
mov r1,#0
str r1,[r0]
mla r0,r9,r7,r8 @ median KD tree address
mov r1,r3 @ search point address
mov r2,#0 @ index
mov r3,#3 @ dimension 2
bl searchNearest
ldr r0,iAdrszMessResult
bl affichageMess
ldr r0,iAdrstNearest
ldr r0,[r0]
mov r1,#3
bl displayCoord
ldr r0,iAdrnbNodeVi
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#3
ldr r1,iAdrszMessVisited
ldr r2,iAdrsZoneConv
ldr r3,iAdrszCarriageReturn
bl displayStrings
ldr r0,iAdriDistance @ best distance address
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#3
ldr r1,iAdrszMessDistance
ldr r2,iAdrsZoneConv
ldr r3,iAdrszCarriageReturn
bl displayStrings
100:
pop {r1-r10,pc}
iAdrKdtreeRand: .int KdtreeRand
iAdrtabPointsRand: .int tabPointsRand
iAdrszMessRandCoor: .int szMessRandCoor
iNbPointsRand: .int NBPOINTSRAND
/***************************************************/
/* init KN tree */
/***************************************************/
/* r0 array points */
/* r1 array tree address */
/* r2 points number */
/* r3 dimension */
initKDTree:
push {r1-r9,lr} @ save des registres
mov r8,#0 @ points indice
mov r4,#0 @ node tree indice
mov r6,#nodeKD_end @ structure size
1:
mla r5,r4,r6,r1 @ compute node address
mov r9,#0 @ index value
2:
ldr r7,[r0,r8,lsl #2] @ load one point coord
str r7,[r5,r9,lsl #2] @ store in node value
add r8,r8,#1 @ next point
add r9,r9,#1 @ next node value
cmp r9,r3 @ = dimension ?
blt 2b @ no loop
mov r7,#-1 @ init pointer left and right
str r7,[r5,#nodeKD_left]
str r7,[r5,#nodeKD_right]
add r4,r4,#1 @ increment node tree indice
cmp r8,r2 @ end points ?
blt 1b
100:
pop {r1-r9,pc}
/***************************************************/
/* create KD tree */
/***************************************************/
/* r0 array tree address */
/* r1 start index */
/* r2 end index
/* r3 level */
/* r4 dimention */
createTree:
push {r1-r12,lr} @ save des registres
cmp r1,r2 @ if start = end -> return -1
movge r0,#-1
bge 100f
add r5,r1,#1 @ if start + 1 = end -> return start
cmp r5,r2
moveq r0,r1
beq 100f
mov r8,r0 @ save address
mov r7,r1 @ save start index
mov r12,r2 @ save end index
mov r5,r3 @ save level
mov r10,r4 @ save dimension
mov r9,#nodeKD_end @ node structure size
mov r1,r7 @ start
mov r2,r12 @ end
bl findMedian
cmp r0,#0 @
movlt r0,#-1
blt 100f
mov r6,r0 @ save indice median
add r5,r5,#1 @ compute new value index
cmp r5,r10 @ => dimension ?
movge r5,#0
mov r0,r8 @ tree address
mov r1,r7 @ start
mov r2,r6 @ end = median
mov r3,r5 @ index
mov r4,r10 @ dimension
bl createTree
mla r1,r6,r9,r8 @ compute median address
cmp r0,#-1 @ left address is ok ?
mlane r0,r9,r0,r8 @ yes compute address
str r0,[r1,#nodeKD_left] @ and store
mov r0,r8 @ KDtree address
add r1,r6,#1 @ start = indice median + 1
mov r2,r12 @ end
mov r3,r5 @ index
mov r4,r10 @ dimension
bl createTree
mla r1,r6,r9,r8 @ compute median address
cmp r0,#-1 @ indice right ok ?
mlane r0,r9,r0,r8 @ yes compute address
str r0,[r1,#nodeKD_right] @ and store in pointer
mov r0,r6 @ return indice median node
100:
pop {r1-r12,pc}
/***************************************************/
/* find median and sort points */
/***************************************************/
/* r0 tree address */
/* r1 start tree indice
/* r2 end tree indice */
/* r3 indice */
/* r0 return median point index */
findMedian:
push {r1-r12,lr} @ save des registres
cmp r2,r1
movle r0,#-1
ble 100f
mov r7,#nodeKD_end @ node size
add r5,r1,#1 @ next node address
cmp r2,r5 @ equal to end ?
moveq r0,r1
beq 100f @ yes return
mov r8,r1 @ save start
mov r12,r0 @ save tree address
add r4,r2,r1 @ end + start
lsr r9,r4,#1 @ divide by 2 = median index
mla r10,r7,r9,r0 @ mediam md address
lsl r5,r3,#2 @ index * 4
1:
cmp r2,r8 @ end <= start
movle r0,r2 @ stop ?
ble 100f
add r6,r10,#nodeKD_val
add r11,r6,r5 @ add shift index
ldr r6,[r11] @ load pivot value
mov r0,r10 @ median address
sub r1,r2,#1 @ compute address end - 1
mul r1,r7,r1
add r1,r1,r12
bl inversion @ inversion median and end - 1
mov r11,r8 @ store=indice start
mov r4,r8 @ p =indice start
2:
cmp r4,r2 @ compare p and end
bge 5f
mla r3,r4,r7,r12 @ compute p address
add r3,r3,r5 @ add shift index
ldr r0,[r3] @ load value
cmp r0,r6 @ compare to pivot
bge 4f
cmp r4,r11 @ compare p et store
beq 3f
mla r0,r4,r7,r12 @ compute p address
mla r1,r11,r7,r12 @ compute store address
bl inversion @ inversion p and store
3:
add r11,r11,#1 @ increment store
4:
add r4,r4,#1 @ increment p
b 2b
5:
moveq r0,r9 @ equal return median index
beq 100f
mla r0,r11,r7,r12 @ store address
sub r1,r2,#1 @ end - 1
mla r1,r7,r1,r12 @ compute address
bl inversion @ inversion store and end - 1
ldr r0,[r0,#nodeKD_val] @ load store value
add r0,r0,r5 @ add shift index
ldr r1,[r10,#nodeKD_val] @ load median value
add r1,r1,r5 @ add shift index
cmp r0,r1 @ compare values
moveq r0,r9 @ equal return median index
beq 100f
cmp r11,r9 @ compare index store and median
movgt r2,r11 @ new end
movle r8,r11 @ new start
b 1b @ and loop
100:
pop {r1-r12,pc}
/***************************************************/
/* compute distance into 2 points */
/***************************************************/
/* r0 tree node address */
/* r1 search points address */
/* r2 dimension */
distance:
push {r3-r7,lr} @ save des registres
add r0,#nodeKD_val @ root node values array address
add r1,#nodeKD_val @ search node values array addresse
mov r3,#0 @ first value index
mov r7,#0 @ init distance
1:
ldr r4,[r0,r3,lsl #2] @ load value
ldr r5,[r1,r3,lsl #2] @ load value
sub r6,r5,r4 @ différence
add r3,r3,#1
mla r7,r6,r6,r7 @ compute square TODO: overflow
cmp r3,r2 @ end ?
blt 1b @ no -> loop
mov r0,r7 @ return distance
100:
pop {r3-r7,pc}
/***************************************************/
/* search nearest point */
/***************************************************/
/* r0 tree address */
/* r1 search points address */
/* r2 index */
/* r3 dimension */
searchNearest:
push {r1-r12,lr} @ save des registres
cmp r0,#-1
beq 100f
mov r7,r0 @ start with median
mov r8,r1 @ save serach point address
lsl r9,r2,#2 @ shift index
mov r10,r3 @ save dimension
mov r2,r3 @ dimension
bl distance @ compute distance
mov r11,r0
ldr r1,[r7,r9]
ldr r12,[r8,r9]
sub r12,r1
mul r6,r12,r12 @ distance axis
ldr r4,iAdriDistance
ldr r5,[r4]
cmp r5,#0 @ first distance ?
moveq r5,r11 @ new best distance
moveq r3,r7 @ new best node
beq 1f
cmp r11,r5 @ compare new distance and best distance
bgt 2f
mov r5,r11 @ new best distance
mov r3,r7 @ new best node
1:
str r5,[r4] @ store new best distance
ldr r4,iAdrstNearest @ and store best node address
str r3,[r4]
2:
ldr r1,iAdrnbNodeVi @ increment visited node
ldr r3,[r1]
add r3,r3,#1
str r3,[r1]
cmp r5,#0 @ distance = 0 -> end @
beq 100f
cmp r12,#0 @ else search in childen tree
ldrlt r0,[r7,#nodeKD_left]
ldrge r0,[r7,#nodeKD_right]
mov r1,r8
lsr r2,r9,#2
add r2,r2,#1
cmp r2,r10
movge r2,#0
mov r3,r10
bl searchNearest
ldr r4,iAdriDistance @ best distance
ldr r5,[r4]
cmp r6,r5 @ compare distance
bge 100f
cmp r12,#0 @ else search in childen tree
ldrge r0,[r7,#nodeKD_left]
ldrlt r0,[r7,#nodeKD_right]
bl searchNearest
100:
pop {r1-r12,pc}
iAdrstNearest: .int stNearest
iAdriDistance: .int iDistance
iAdrnbNodeVi: .int nbNodeVi
/***************************************************/
/* inversion */
/***************************************************/
/* r0 tree address */
/* r1 tree */
inversion:
push {r0-r4,lr} @ save des registres
add r0,#nodeKD_val
add r1,#nodeKD_val
mov r2,#0
1:
ldr r4,[r0,r2,lsl #2]
ldr r3,[r1,r2,lsl #2]
str r3,[r0,r2,lsl #2]
str r4,[r1,r2,lsl #2]
add r2,r2,#1
cmp r2,#MAXI
blt 1b
100:
pop {r0-r4,pc}
/***************************************************/
/* display tree */
/***************************************************/
/* r0 tree address */
/* r1 dimension */
displayTree:
push {r2-r12,lr} @ save des registres
mov r10,r0
mov r7,r1
mov r11,#0
mov r12,#nodeKD_end
1:
mla r9,r12,r11,r10
mov r0,r9
ldr r1,iAdrsBufferConv16
bl conversion16
mov r0,#2
ldr r1,iAdrszMessAddressTree
ldr r2,iAdrsBufferConv16
bl displayStrings
mov r8,#0
2:
add r4,r9,#nodeKD_val
ldr r0,[r4,r8,lsl #2]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#2
ldr r1,iAdrszMessTreeValue
ldr r2,iAdrsZoneConv
bl displayStrings
add r8,r8,#1
cmp r8,r7
blt 2b
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r0,r9,#nodeKD_left
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion16
add r0,r9,#nodeKD_right
ldr r0,[r0]
ldr r1,iAdrsZoneConv1
bl conversion16
mov r0,#5
ldr r1,iAdrszMessLeft
ldr r2,iAdrsZoneConv
ldr r3,iAdrszMessRight
ldr r4,iAdrsZoneConv1
push {r4}
ldr r4,iAdrszCarriageReturn
push {r4}
bl displayStrings
add sp,sp,#8
add r11,r11,#1
cmp r11,#NBPOINTS / 2
blt 1b
100:
pop {r2-r12,pc}
iAdrszMessAddressTree: .int szMessAddressTree
iAdrszMessTreeValue: .int szMessTreeValue
iAdrsBufferConv16: .int sBufferConv16
iAdrszMessLeft: .int szMessLeft
iAdrszMessRight: .int szMessRight
iAdrsZoneConv1: .int sZoneConv1
/***************************************************/
/* display node coordonnées */
/***************************************************/
/* r0 node address */
/* r1 dimension */
displayCoord:
push {r1-r5,lr} @ save des registres
add r4,r0,#nodeKD_val
mov r3,r1 @ save dimension
mov r5,#0
1:
ldr r0,[r4,r5,lsl #2]
ldr r1,iAdrsZoneConv
bl conversion10
mov r0,#2
ldr r1,iAdrszMessTreeValue
ldr r2,iAdrsZoneConv
bl displayStrings
add r5,r5,#1
cmp r5,r3
blt 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r1-r5,pc}
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
cmp r0,#0
beq 100f
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"

View File

@ -0,0 +1,30 @@
let m = 7
let n = 1
for e = 2 to m
if e = 2 then
let s = 0
else
let s = 4
endif
let n = (n + 1) * 2 - 1
for i = 1 to e - 2
let s = (s * s - 2) % n
next i
if s = 0 then
print e, " ",
endif
next e

View File

@ -1,19 +1,51 @@
for y0 = 0 to 299
cy = (y0 - 150) / 120
for x0 = 0 to 299
cx = (x0 - 220) / 120
x = 0 ; y = 0 ; iter = 0
while iter < 64 and x * x + y * y < 4
h = x * x - y * y + cx
y = 2 * x * y + cy
x = h
iter += 1
.
if iter = 64
iter = 0
.
color3 iter / 16 0 0
move x0 / 3 y0 / 3
rect 0.4 0.4
.
center_x = 220
center_y = 150
scale = 150
background 000
textsize 2
#
proc draw . .
clear
for scr_y = 0 to 299
cy = (scr_y - center_y) / scale
for scr_x = 0 to 299
cx = (scr_x - center_x) / scale
x = 0 ; y = 0 ; iter = 0
repeat
xx = x * x
yy = y * y
until xx + yy >= 4 or iter = 128
h = xx - yy + cx
y = 2 * x * y + cy
x = h
iter += 1
.
if iter < 128
color3 iter / 32 iter / 128 0
move scr_x / 3 scr_y / 3
rect 0.4 0.4
.
.
.
color 990
move 1 1
text "Short press to zoom in, long to zoom out"
.
on mouse_down
time0 = systime
.
on mouse_up
center_x += 150 - mouse_x * 3
center_y += 150 - mouse_y * 3
if systime - time0 < 0.3
center_x -= 150 - center_x
center_y -= 150 - center_y
scale *= 2
else
center_x += (150 - center_x) / 2
center_y += (150 - center_y) / 2
scale /= 2
.
call draw
.
call draw

View File

@ -0,0 +1,34 @@
void local fn MertensFunction
long mertens(1000), n, k, crossesTotal = 0, zerosTotal = 0
mertens(1) = 1
for n = 2 to 1000
mertens(n) = 1
for k = 2 to n
mertens(n) = mertens(n) - mertens(n/k)
next
next
printf @"First 99 Mertens numbers:\n \b"
for n = 1 to 99
printf @"%3ld \b", mertens(n)
if ( n mod 10 == 9 ) then print
next
for n = 1 to 1000
if ( mertens(n) == 0 )
zerosTotal++
if mertens(n-1) != 0 then crossesTotal++
end if
next
print
printf @"mertens(n) array is zero %ld times.", zerosTotal
printf @"mertens(n) array crosses zero %ld times.", crossesTotal
end fn
fn MertensFunction
HandleEvents

View File

@ -0,0 +1,3 @@
OutputForm[
x^100 + x + 1 /. x -> FiniteField[13][10]
]

View File

@ -1,19 +1,19 @@
ordinal = function(n)
if n > 3 and n < 20 then return n + "th"
if n % 100 > 3 and n %100 < 20 then return n + "th"
if n % 10 == 1 then return n + "st"
if n % 10 == 2 then return n + "nd"
if n % 10 == 3 then return n + "rd"
return n + "th"
end function
out = []
test = function(from, to)
out = []
for i in range(from, to)
out.push ordinal(i)
end for
print out.join
end function
test 0, 25
test 250, 265
test 1000, 1025
print out.join

View File

@ -0,0 +1,61 @@
Function ownCalcPass(password As String, nonce As String) As Integer
Dim As Boolean start = True
Dim As Integer b, num1 = 0, num2 = 0
For b = 0 To Len(nonce)
Dim As String c = Mid(nonce,b,1)
If c <> "0" And start Then
num2 = Cint(password)
start = False
End If
Select Case c
Case "1"
num1 = (num2 And &HFFFFFF80) Shr 7
num2 = num2 Shl 25
Case "2"
num1 = (num2 And &HFFFFFFF0) Shr 4
num2 = num2 Shl 28
Case "3"
num1 = (num2 And &HFFFFFFF8) Shr 3
num2 = num2 Shl 29
Case "4"
num1 = num2 Shl 1
num2 = num2 Shr 31
Case "5"
num1 = num2 Shl 5
num2 = num2 Shr 27
Case "6"
num1 = num2 Shl 12
num2 = num2 Shr 20
Case "7"
num1 = num2 And &H0000FF00 Or ((num2 And &H000000FF) Shl 24) Or ((num2 And &H00FF0000) Shr 16)
num2 = (num2 And &HFF000000) Shr 8
Case "8"
num1 = (num2 And &H0000FFFF) Shl 16 Or (num2 Shr 24)
num2 = (num2 And &H00FF0000) Shr 8
Case "9"
num1 = Not num2
Case Else
num1 = num2
End Select
num1 And= &HFFFFFFFF
num2 And= &HFFFFFFFF
If c <> "0" And c <> "9" Then num1 Or= num2
num2 = num1
Next b
Return num1
End Function
Sub testPasswordCalc(password As String, nonce As String, expected As Integer)
Dim As Integer res = ownCalcPass(password, nonce)
Print Iif(res = expected, "PASS ", "FAIL ");
Print Using "& & & ##########"; password; nonce; res; expected
End Sub
testPasswordCalc("12345", "603356072", 25280520)
testPasswordCalc("12345", "410501656", 119537670)
testPasswordCalc("12345", "630292165", 4269684735)
Sleep

View File

@ -135,7 +135,7 @@
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">else</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">pals</span><span style="color: #0000FF;">,</span><span style="color: #000000;">palcount</span><span style="color: #0000FF;">,</span><span style="color: #000000;">skipn</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">palindromicgapfuls</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pals</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lhs</span><span style="color: #0000FF;">&(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">palcount</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">to_skip</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">r2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dd</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">pals</span><span style="color: #0000FF;">,</span><span style="color: #000000;">palcount</span><span style="color: #0000FF;">,</span><span style="color: #000000;">skipn</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">palindromicgapfuls</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pals</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lhs</span><span style="color: #0000FF;">&(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">),</span><span style="color: #000000;">palcount</span><span style="color: #0000FF;">,</span><span style="color: #000000;">to_skip</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dd</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">skip</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">skipn</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">palcount</span><span style="color: #0000FF;">==</span><span style="color: #000000;">count</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>

View File

@ -0,0 +1,73 @@
define limit = 20, loops = 0
dim list[limit]
input "loops?", loops
for x = 1 to loops
let n = x
print n, " : ",
gosub collectprimefactors
for y = 0 to c
if list[y] then
print list[y], " ",
let list[y] = 0
endif
next y
print ""
next x
end
sub collectprimefactors
let c = 0
do
if int(n mod 2) = 0 then
let n = int(n / 2)
let list[c] = 2
let c = c + 1
endif
wait
loop int(n mod 2) = 0
for i = 3 to sqrt(n) step 2
do
if int(n mod i) = 0 then
let n = int(n / i)
let list[c] = i
let c = c + 1
endif
wait
loop int(n mod i) = 0
next i
if n > 2 then
let list[c] = n
let c = c + 1
endif
return

View File

@ -3,6 +3,6 @@ pub fn main() anyerror!void {
for (0..100_000_000) |number| {
if (isSelfDescribing(@intCast(number)))
_ = try stdout.print("{}\n", .{number});
try stdout.print("{}\n", .{number});
}
}

View File

@ -6,8 +6,8 @@ pub fn main() !void {
var y = size;
while (y > 0) {
y -= 1;
for (0..y) |_| _ = try stdout.writeByte(' ');
for (0..size - y) |x| _ = try stdout.writeAll(if (x & y != 0) " " else "* ");
_ = try stdout.writeByte('\n');
for (0..y) |_| try stdout.writeByte(' ');
for (0..size - y) |x| try stdout.writeAll(if (x & y != 0) " " else "* ");
try stdout.writeByte('\n');
}
}

View File

@ -7,10 +7,10 @@ fn sierpinski_triangle(allocator: Allocator, writer: anytype, n: u8) !void {
b[len >> 1] = '*';
_ = try writer.print("{s}\n", .{b});
try writer.print("{s}\n", .{b});
for (0..len / 2 - 1) |_| {
try rule_90(allocator, b);
_ = try writer.print("{s}\n", .{b});
try writer.print("{s}\n", .{b});
}
}

View File

@ -0,0 +1,73 @@
def ScrW=320, ScrH=200;
def Pi = 3.141592654;
def D2R = Pi/180.0;
real Dir, PosX, PosY;
int Pen;
def \Pen\ Up, Down;
proc Turn(Ang);
real Ang;
Dir:= Dir + Ang*D2R;
proc MoveTo(Dist);
real Dist;
[PosX:= PosX + Dist*Cos(Dir);
PosY:= PosY + Dist*Sin(Dir);
if Pen = Down then
Line(ScrW/2+fix(PosX), ScrH/2-fix(PosY), $0F \white\)
else
Move(ScrW/2+fix(PosX), ScrH/2-fix(PosY));
];
proc Rectangle(Width, Height);
real Width, Height;
int N;
[for N:= 1 to 2 do
[MoveTo(Width);
Turn(90.0);
MoveTo(Height);
Turn(90.0);
];
];
proc BarGraph(List, Len, Size);
real List; int Len; real Size;
real PosX0;
int N;
def BarWidth = 0.4;
[PosX0:= PosX;
for N:= 0 to Len-1 do
[Rectangle(Size*BarWidth, List(N)*Size);
MoveTo(Size*BarWidth);
];
PosX:= PosX0;
];
proc Triangle(Size);
real Size;
int N;
[for N:= 1 to 3 do
[MoveTo(Size);
Turn(-120.0);
];
];
proc Square(Size);
real Size;
Rectangle(Size, Size);
proc House(Size);
real Size;
[Turn(180.0);
Square(Size);
Triangle(Size);
Turn(180.0);
];
[SetVid($13); \set VGA graphics
Move(ScrW/2, ScrH/2); \start Line at center
Dir:= 0.0; PosX:= 0.0; PosY:= 0.0; Pen:= Down;
House(80.0);
Pen:= Up; MoveTo(10.0); Pen:= Down;
BarGraph([0.5, 1.0/3.0, 2.0, 1.3, 0.5], 5, 50.0);
]

View File

@ -1,8 +1,8 @@
class Node<T>{
var data:T?=nil
var next:Node?=nil
init(input:T){
data=input
next=nil
var data: T = nil
var next: Node? = nil
init(input: T){
data = input
next = nil
}
}

View File

@ -1,3 +1,3 @@
case=. 1 * (0 = # x=. @:[) + 2 * (0 = # y=. @:])
case=. (0 = # x=. @:[) + 2 * (0 = # y=. @:])
merge=. ({.x , }.x $: ])`(({.y , }.y $: [))@.({.x > {.y)`]`[@.case
mergesort=. (>: o ? o # ($: o {. merge $: (o=. @:) }.) ]) ^: (1 < #)
mergesort=. (<. o -: o # ($: o {. merge $: (o=. @:) }.) ]) ^:(1 < #)

View File

@ -31,11 +31,13 @@ As written, this example assumes ASCII or a superset of it, such as any of the L
The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:
<pre>start:
0f 11 ff subleq (zero), (message), -1
11 ff ff subleq (message), -1, -1 ; output character at message
10 01 ff subleq (neg1), (start+1), -1
10 03 ff subleq (neg1), (start+3), -1
0f 0f 00 subleq (zero), (zero), start
0f 11 ff subleq (zero), (message), -1 ; subtract 0 from next character value to print;
; terminate if it's <=0
11 ff ff subleq (message), -1, -1 ; output character
10 01 ff subleq (neg1), (start+1), -1 ; modify above two instructions by subtracting -1
10 03 ff subleq (neg1), (start+3), -1 ; (adding 1) to their target addresses
0f 0f 00 subleq (zero), (zero), start ; if 0-0 <= 0 (i.e. always) goto start
; useful constants
zero:
00 .data 0

View File

@ -27,5 +27,3 @@ do
endif
loop num < nums
end

View File

@ -0,0 +1,39 @@
MODULE TauNumbers;
IMPORT Out;
CONST
MaxNum = 1100;
NumTau = 100;
VAR
divcount: ARRAY MaxNum OF LONGINT; (* enough to generate 100 Tau numbers *)
seen,n:LONGINT; (* how many Tau numbers to generate *)
(* Find the amount of divisors for each number beforehand *)
PROCEDURE CountDivisors;
VAR i,j:LONGINT;
BEGIN
FOR i := 0 TO LEN(divcount)-1 DO divcount[i] := 1 END;
FOR i := 2 TO LEN(divcount)-1 DO
j := i;
WHILE j <= LEN(divcount)-1 DO (* j is divisible by i *)
INC(divcount[j]);
INC(j,i) (* next multiple of i *)
END
END;
END CountDivisors;
BEGIN
CountDivisors;
n := 1;
seen := 0;
WHILE seen < NumTau DO
IF n MOD divcount[n] = 0 THEN
Out.Int(n,5);
INC(seen);
IF seen MOD 10 = 0 THEN Out.Ln END
END;
INC(n)
END
END TauNumbers.

View File

@ -0,0 +1,32 @@
10 let count = 0
20 let num = 0
30 let modulus = 0
40 let nums = 100
50 let tau = 0
60 rem do
70 let count = count + 1
80 let tau = 0
90 let modulus = 1
100 rem do
100 if count mod modulus <> 0 then 130
120 let tau = tau + 1
130 rem endif
140 let modulus = modulus + 1
150 if modulus < count + 1 then 100
160 if count mod tau <> 0 then 190
170 let num = num + 1
180 print count, tab,
190 rem endif
200 if num < nums then 60

View File

@ -0,0 +1,27 @@
10 DEFINT A-Z: DIM B$(2): B$(0)="No": B$(1)="Yes"
20 PRINT " N Totient Prime"
30 FOR N=1 TO 25
40 GOSUB 200
50 P=-(T=N-1)
60 C=C+P
70 PRINT USING "## ####### \ \";N;T;B$(P)
80 NEXT N
90 F$="Number of primes up to ######: ####"
100 PRINT USING F$;25;C
110 FOR N=26 TO 10000
120 GOSUB 200
130 C=C-(T=N-1)
140 IF N=100 OR N=1000 OR N=10000 THEN PRINT USING F$;N;C
150 NEXT N
160 END
200 REM T = TOTIENT(N)
210 T=N: Z=N
220 I=2: GOSUB 270
230 I=3
240 IF I*I<=Z THEN GOSUB 270: I=I+2: GOTO 240
250 IF Z>1 THEN T=T-T\Z
260 RETURN
270 IF Z MOD I<>0 THEN RETURN
280 IF Z MOD I=0 THEN Z = Z\I: GOTO 280
290 T = T-T\I
300 RETURN

View File

@ -0,0 +1,31 @@
get "libhdr"
let totient(n) = valof
$( let tot = n and i = 2
while i*i <= n
$( if n rem i = 0
$( while n rem i = 0 do n := n / i
tot := tot - tot/i
$)
if i=2 then i:=1
i := i+2
$)
resultis n>1 -> tot-tot/n, tot
$)
let start() be
$( let count = 0
writes(" N Totient Prime*N")
for n = 1 to 25
$( let tot = totient(n)
let prime = n-1 = tot
if prime then count := count + 1
writef("%I2 %I7 %S*N", n, tot, prime -> " Yes", " No")
$)
writef("Number of primes up to %I6: %I4*N", 25, count)
for n = 26 to 10000
$( if totient(n) = n-1 then count := count + 1
if n = 100 | n = 1000 | n = 10000 then
writef("Number of primes up to %I6: %I4*N", n, count)
$)
$)

View File

@ -0,0 +1,50 @@
totient = proc (n: int) returns (int)
tot: int := n
i: int := 2
while i*i <= n do
if n//i = 0 then
while n//i = 0 do
n := n/i
end
tot := tot-tot/i
end
if i=2 then i:=1 end
i := i+2
end
if n>1 then
tot := tot-tot/n
end
return(tot)
end totient
start_up = proc ()
po: stream := stream$primary_output()
count: int := 0
stream$putl(po, " N Totient Prime")
for n: int in int$from_to(1, 25) do
tot: int := totient(n)
stream$putright(po, int$unparse(n), 2)
stream$putright(po, int$unparse(tot), 9)
if n-1 = tot then
stream$putright(po, "Yes", 7)
count := count + 1
else
stream$putright(po, "No", 7)
end
stream$putl(po, "")
end
stream$putl(po, "Number of primes up to 25:\t" || int$unparse(count))
for n: int in int$from_to(26, 100000) do
if totient(n) = n-1 then
count := count + 1
end
if n = 100 cor n = 1000 cor n // 10000 = 0 then
stream$putl(po, "Number of primes up to "
|| int$unparse(n) || ":\t"
|| int$unparse(count))
end
end
end start_up

View File

@ -0,0 +1,93 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. TOTIENT-FUNCTION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 TOTIENT-CALCULATION.
03 N PIC 9(6).
03 TOTIENT PIC 9(6).
03 DIVISOR PIC 9(6).
03 DIV-SQUARE PIC 9(6).
03 MODULUS PIC 9(6).
01 LOOP-VARS.
03 PRIME-COUNT PIC 9(4).
03 CURRENT-N PIC 9(6).
03 PRIME-TOTIENT PIC 9(6).
01 OUTPUTFORMAT.
03 HEADER PIC X(20) VALUE " N Totient Prime?".
03 TOTIENT-ROW.
05 OUT-N PIC Z9.
05 FILLER PIC XX VALUE SPACES.
05 OUT-TOTIENT PIC Z(6)9.
05 FILLER PIC XX VALUE SPACES.
05 OUT-PRIME PIC X(5).
03 PRIME-COUNT-ROW.
05 FILLER PIC X(22) VALUE "Number of primes up to".
05 OUT-PRMTO PIC Z(5)9.
05 FILLER PIC XX VALUE ": ".
05 OUT-PRMCNT PIC ZZZ9.
PROCEDURE DIVISION.
BEGIN.
MOVE ZERO TO PRIME-COUNT.
DISPLAY HEADER.
PERFORM SHOW-SMALL-TOTIENT
VARYING CURRENT-N FROM 1 BY 1
UNTIL CURRENT-N IS GREATER THAN 25.
MOVE 25 TO OUT-PRMTO.
MOVE PRIME-COUNT TO OUT-PRMCNT.
DISPLAY PRIME-COUNT-ROW.
PERFORM COUNT-PRIMES
VARYING CURRENT-N FROM 26 BY 1
UNTIL CURRENT-N IS GREATER THAN 10000.
STOP RUN.
SHOW-SMALL-TOTIENT.
MOVE CURRENT-N TO N.
PERFORM CALCULATE-TOTIENT.
MOVE CURRENT-N TO OUT-N.
MOVE TOTIENT TO OUT-TOTIENT.
MOVE "No" TO OUT-PRIME.
SUBTRACT 1 FROM CURRENT-N GIVING PRIME-TOTIENT.
IF TOTIENT IS EQUAL TO PRIME-TOTIENT,
MOVE "Yes" TO OUT-PRIME,
ADD 1 TO PRIME-COUNT.
DISPLAY TOTIENT-ROW.
COUNT-PRIMES.
MOVE CURRENT-N TO N.
PERFORM CALCULATE-TOTIENT.
SUBTRACT 1 FROM CURRENT-N GIVING PRIME-TOTIENT.
IF TOTIENT IS EQUAL TO PRIME-TOTIENT, ADD 1 TO PRIME-COUNT.
IF CURRENT-N IS EQUAL TO 100 OR 1000 OR 10000,
MOVE CURRENT-N TO OUT-PRMTO,
MOVE PRIME-COUNT TO OUT-PRMCNT,
DISPLAY PRIME-COUNT-ROW.
CALCULATE-TOTIENT.
MOVE N TO TOTIENT.
MOVE 2 TO DIVISOR.
MOVE 4 TO DIV-SQUARE.
PERFORM DIVIDE-STEP.
PERFORM DIVIDE-STEP
VARYING DIVISOR FROM 3 BY 2
UNTIL DIV-SQUARE IS GREATER THAN N.
IF N IS GREATER THAN 1,
COMPUTE TOTIENT = TOTIENT - TOTIENT / N.
DIVIDE-STEP.
MULTIPLY DIVISOR BY DIVISOR GIVING DIV-SQUARE.
DIVIDE N BY DIVISOR GIVING MODULUS.
MULTIPLY DIVISOR BY MODULUS.
SUBTRACT MODULUS FROM N GIVING MODULUS.
IF MODULUS IS ZERO,
PERFORM DIVIDE-OUT UNTIL MODULUS IS NOT ZERO,
COMPUTE TOTIENT = TOTIENT - TOTIENT / DIVISOR.
DIVIDE-OUT.
DIVIDE DIVISOR INTO N.
DIVIDE N BY DIVISOR GIVING MODULUS.
MULTIPLY DIVISOR BY MODULUS.
SUBTRACT MODULUS FROM N GIVING MODULUS.

View File

@ -0,0 +1,61 @@
include "cowgol.coh";
sub totient(n: uint32): (tot: uint32) is
tot := n;
var i: uint32 := 2;
while i*i <= n loop
if n%i == 0 then
while n%i == 0 loop
n := n/i;
end loop;
tot := tot - tot/i;
end if;
if i == 2 then
i := 1;
end if;
i := i + 2;
end loop;
if n > 1 then
tot := tot - tot/n;
end if;
end sub;
var count: uint16 := 0;
print("N\tTotient\tPrime\n");
var n: uint32 := 1;
while n <= 25 loop
var tot := totient(n);
print_i32(n);
print_char('\t');
print_i32(tot);
print_char('\t');
if n-1 == tot then
count := count + 1;
print("Yes\n");
else
print("No\n");
end if;
n := n + 1;
end loop;
print("Number of primes up to 25:\t");
print_i16(count);
print_nl();
while n <= 100000 loop
tot := totient(n);
if n-1 == tot then
count := count + 1;
end if;
if n == 100 or n == 1000 or n % 10000 == 0 then
print("Number of primes up to ");
print_i32(n);
print(":\t");
print_i16(count);
print_nl();
end if;
n := n + 1;
end loop;

View File

@ -0,0 +1,39 @@
proc totient(word n) word:
word tot, i;
tot := n;
i := 2;
while i*i <= n do
if n%i = 0 then
while n%i = 0 do n := n/i od;
tot := tot - tot/i
fi;
if i=2 then i:=1 fi;
i := i+2
od;
if n>1 then
tot - tot/n
else
tot
fi
corp
proc main() void:
word count, n, tot;
bool prime;
count := 0;
writeln(" N Totient Prime");
for n from 1 upto 25 do
tot := totient(n);
prime := n-1 = tot;
if prime then count := count+1 fi;
writeln(n:2, " ", tot:7, " ", if prime then " Yes" else " No" fi)
od;
writeln("Number of primes up to ",25:6,": ",count:4);
for n from 25 upto 10000 do
if totient(n) = n-1 then count := count+1 fi;
if n=100 or n=1000 or n=10000 then
writeln("Number of primes up to ",n:6,": ",count:4)
fi
od
corp

View File

@ -0,0 +1,45 @@
NORMAL MODE IS INTEGER
BOOLEAN PRM
INTERNAL FUNCTION(A,B)
ENTRY TO REM.
FUNCTION RETURN A-A/B*B
END OF FUNCTION
INTERNAL FUNCTION(NN)
ENTRY TO TOTENT.
N = NN
TOT = N
THROUGH STEP, FOR I=2, 2, I*I.G.N
WHENEVER REM.(N,I).E.0
THROUGH DIV, FOR N=N, 0, REM.(N,I).NE.0
DIV N = N/I
TOT = TOT-TOT/I
END OF CONDITIONAL
WHENEVER I.E.2, I=1
STEP CONTINUE
WHENEVER N.G.1, TOT = TOT-TOT/N
FUNCTION RETURN TOT
END OF FUNCTION
COUNT = 0
PRINT FORMAT HEADER
THROUGH FRST25, FOR KN=1, 1, KN.G.25
KTOT = TOTENT.(KN)
PRM = KTOT.E.KN-1
WHENEVER PRM, COUNT = COUNT + 1
FRST25 PRINT FORMAT NUMTOT,KN,KTOT,PRM
PRINT FORMAT NUMPRM,25,COUNT
THROUGH CNTPRM, FOR KN=26, 1, KN.G.100000
KTOT = TOTENT.(KN)
WHENEVER KTOT.E.KN-1, COUNT = COUNT+1
WHENEVER KN.E.100 .OR. KN.E.1000 .OR. REM.(KN,10000).E.0,
0 PRINT FORMAT NUMPRM,KN,COUNT
CNTPRM CONTINUE
VECTOR VALUES HEADER = $19H N TOTIENT PRIME*$
VECTOR VALUES NUMTOT = $I2,S2,I7,S2,I5*$
VECTOR VALUES NUMPRM = $22HNUMBER OF PRIMES UP TO,I7,1H:,I6*$
END OF PROGRAM

View File

@ -0,0 +1,25 @@
main :: [sys_message]
main = [Stdout (lay (map showline [1..25])),
Stdout (lay (map countprimes (25:map (10^) [2..5])))]
countprimes :: num->[char]
countprimes n = "There are " ++ show amount ++ " primes up to " ++ show n
where amount = #filter prime [2..n]
showline :: num->[char]
showline n = "phi(" ++ show n ++ ") = " ++ show (totient n) ++ ", " ++ kind
where kind = "prime", if prime n
= "composite", otherwise
prime :: num->bool
prime n = totient n = n - 1
totient :: num->num
totient n = loop n n (2:[3, 5..])
where loop tot n (d:ds)
= tot, if n<=1
= tot - tot div n, if d*d > n
= loop tot n ds, if n mod d ~= 0
= loop (tot - tot div d) (remfac n d) ds, otherwise
remfac n d = n, if n mod d ~= 0
= remfac (n div d) d, otherwise

View File

@ -0,0 +1,62 @@
MODULE TotientFunction;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
VAR count, n, tot: CARDINAL;
PROCEDURE totient(n: CARDINAL): CARDINAL;
VAR tot, i: CARDINAL;
BEGIN
tot := n;
i := 2;
WHILE i*i <= n DO
IF n MOD i = 0 THEN
WHILE n MOD i = 0 DO
n := n DIV i
END;
DEC(tot, tot DIV i)
END;
IF i=2 THEN i := 1 END;
INC(i, 2)
END;
IF n>1 THEN
DEC(tot, tot DIV n)
END;
RETURN tot
END totient;
PROCEDURE ShowPrimeCount(n, count: CARDINAL);
BEGIN
WriteString("Number of primes up to");
WriteCard(n, 6);
WriteString(": ");
WriteCard(count, 4);
WriteLn
END ShowPrimeCount;
BEGIN
count := 0;
WriteString(" N Totient Prime");
WriteLn;
FOR n := 1 TO 25 DO
tot := totient(n);
WriteCard(n, 2);
WriteCard(tot, 9);
IF tot = n-1 THEN
WriteString(" Yes");
INC(count)
ELSE
WriteString(" No")
END;
WriteLn
END;
ShowPrimeCount(25, count);
FOR n := 26 TO 10000 DO
IF totient(n) = n-1 THEN INC(count) END;
IF (n=100) OR (n=1000) OR (n=10000) THEN
ShowPrimeCount(n, count)
END;
END
END TotientFunction.

View File

@ -0,0 +1,41 @@
totientFunction: procedure options(main);
totient: procedure(nn) returns(fixed);
declare (nn, n, i, tot) fixed;
n = nn;
tot = n;
do i=2 repeat(i+2) while(i*i <= n);
if mod(n,i) = 0 then do;
do while(mod(n,i) = 0);
n = n / i;
end;
tot = tot - tot / i;
end;
if i=2 then i=1;
end;
if n>1 then tot = tot - tot/n;
return(tot);
end totient;
showPrimeCount: procedure(n, primeCount);
declare (n, primeCount) fixed;
put skip edit('There are', primeCount, ' primes up to', n) (A,F(5),A,F(6));
end showPrimeCount;
declare (n, primeCount, tot) fixed;
do n = 1 to 25;
tot = totient(n);
put edit('phi(', n, ') = ', tot) (A,F(2),A,F(2));
if tot = n-1 then do;
put list('; prime');
primeCount = primeCount + 1;
end;
put skip;
end;
call showPrimeCount(25, primeCount);
do n = 26 to 10000;
if totient(n) = n-1 then primeCount = primeCount + 1;
if n=100 | n=1000 | n=10000 then
call showPrimeCount(n, primeCount);
end;
end totientFunction;

View File

@ -0,0 +1,66 @@
100H:
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUM: PROCEDURE (N);
DECLARE (N, P) ADDRESS, CH BASED P BYTE;
DECLARE S (6) BYTE INITIAL ('.....$');
P = .S(5);
DIGIT:
P = P-1;
CH = '0' + N MOD 10;
IF (N := N/10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUM;
TOTIENT: PROCEDURE (N) ADDRESS;
DECLARE (TOT, N, I) ADDRESS;
TOT = N;
I = 2;
DO WHILE I*I <= N;
IF N MOD I = 0 THEN DO;
DO WHILE (N := N / I) MOD I = 0; END;
TOT = TOT - TOT / I;
END;
IF I=2 THEN I=1;
I = I+2;
END;
IF N > 1 THEN TOT = TOT - TOT / N;
RETURN TOT;
END TOTIENT;
SHOW$PRIME$COUNT: PROCEDURE (N, COUNT);
DECLARE (N, COUNT) ADDRESS;
CALL PRINT(.'THERE ARE $');
CALL PRINT$NUM(COUNT);
CALL PRINT(.' PRIMES UP TO $');
CALL PRINT$NUM(N);
CALL PRINT(.(13,10,'$'));
END SHOW$PRIME$COUNT;
DECLARE (N, TOT) ADDRESS;
DECLARE PRIME$COUNT ADDRESS INITIAL (0);
DO N = 1 TO 25;
CALL PRINT(.'PHI($');
CALL PRINT$NUM(N);
CALL PRINT(.') = $');
CALL PRINT$NUM(TOT := TOTIENT(N));
IF TOT = N-1 THEN DO;
CALL PRINT(.'; PRIME$');
PRIME$COUNT = PRIME$COUNT + 1;
END;
CALL PRINT(.(13,10,'$'));
END;
CALL SHOW$PRIME$COUNT(25, PRIME$COUNT);
DO N = 26 TO 10000;
IF TOTIENT(N) = N-1 THEN
PRIME$COUNT = PRIME$COUNT + 1;
IF N=100 OR N=1000 OR N=10000 THEN
CALL SHOW$PRIME$COUNT(N, PRIME$COUNT);
END;
CALL EXIT;
EOF

View File

@ -1,7 +1,7 @@
require "prime"
def 𝜑(n)
n.prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
n.prime_division.inject(1){|res, (pr, exp)| res * (pr-1) * pr**(exp-1) }
end
1.upto 25 do |n|

View File

@ -0,0 +1,14 @@
for n = 1 to 10
let k = -1
do
let k = k + 2
wait
loop prime(2 ^ (2 ^ n) - k) = 0
print "n = ", n, " k = ", k
next n

View File

@ -0,0 +1,15 @@
# useful.py by xing216
from gmpy2 import is_prime
def useful(n):
k = 1
is_useful = False
while is_useful == False:
if is_prime(2**(2**n) - k):
is_useful = True
break
k += 2
return k
if __name__ == "__main__":
print("n | k")
for i in range(1,14):
print(f"{i:<4}{useful(i)}")

View File

@ -38,5 +38,3 @@ for i = 990 to 999
print list[i]
next i
end

View File

@ -14,9 +14,9 @@ pub fn main() anyerror!void {
const encoded = try vigenere(allocator, text, key, true);
defer allocator.free(encoded);
_ = try stdout.print("{s}\n", .{encoded});
try stdout.print("{s}\n", .{encoded});
const decoded = try vigenere(allocator, encoded, key, false);
defer allocator.free(decoded);
_ = try stdout.print("{s}\n", .{decoded});
try stdout.print("{s}\n", .{decoded});
}