started at ; stage 2 at ; ended at
less is more, so your challenge is to check if a number is prime. as a return to form, submissions can be written in python, c, rust, false, or raku.
edge cases:
APIs:
entry
that takes an int
and returns a bool
int entry(int)
fn entry(x: u32) -> bool
1
or 0
to stdout.entry
that takes an int
and returns a Bool
you can download all the entries
written by indigo (away until 9/26)
submitted at
5 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | [0][0]#{ FALSE Polyglot because why not (Tested on TIO) # All the [0][0]#{ are to create comments in FALSE import sys code = r''' { Get integer from stdin } 0^[$1_>]['0-\10*+^]#% { Store in a } a: { Flag for primality } a;1=b: { Loop from a to 2, if divisible then set flag } a;[1-$1>][$$a;\/*a;=b;|b:]# % { Print result (add one; -1 (not prime) => 0; 0 (prime) => 1) } 1b;+. ''' [0][0]#{ class Interpreter: class Variable: def __init__(self, name): self.name = name class Lambda: def __init__(self, code): self.code = code def __init__(self, code, vars = None, stack = None): self.code = code self.pos = 0 self.vars = vars or dict() self.stack = stack or list() self.input = sys.stdin self.output = sys.stdout def set_input(self, inp): self.input = inp def set_output(self, out): self.output = out def run(self): while True: self.skip_whitespace() if self.current_char() == None: return elif self.current_char() == '{': self.skip_comment() elif self.current_char() == '\'': self.advance() self.stack.append(ord(self.current_char())) self.advance() elif self.current_char() == '$': self.stack.append(self.stack[-1]) self.advance() elif self.current_char() == '%': self.stack.pop() self.advance() elif self.current_char() == '\\': self.swap() self.advance() elif self.current_char() == '@': self.rotate() self.advance() elif self.current_char() == 'ΓΈ': self.pick() self.advance() elif self.current_char() == '+': self.stack.append(self.stack.pop() + self.stack.pop()) self.advance() elif self.current_char() == '-': a = self.stack.pop() self.stack.append(self.stack.pop() - a) self.advance() elif self.current_char() == '*': self.stack.append(self.stack.pop() * self.stack.pop()) self.advance() elif self.current_char() == '/': q = self.stack.pop() self.stack.append(self.stack.pop() // q) self.advance() elif self.current_char() == '_': self.stack.append(-self.stack.pop()) self.advance() elif self.current_char() == '&': self.stack.append(self.stack.pop() & self.stack.pop()) self.advance() elif self.current_char() == '|': self.stack.append(self.stack.pop() | self.stack.pop()) self.advance() elif self.current_char() == '~': self.stack.append(~self.stack.pop()) self.advance() elif self.current_char() == '>': b = self.stack.pop() self.stack.append(-1 if self.stack.pop() > b else 0) self.advance() elif self.current_char() == '=': b = self.stack.pop() self.stack.append(-1 if self.stack.pop() == b else 0) self.advance() elif self.current_char() == '[': self.push_lambda() elif self.current_char() == '#': self.advance() self.while_loop() elif self.current_char().isdigit(): self.push_num() elif self.current_char().isalpha(): self.stack.append(__class__.Variable(self.current_char())) self.advance() elif self.current_char() == ':': var = self.stack.pop() self.vars[var.name] = self.stack.pop() self.advance() elif self.current_char() == ';': var = self.stack.pop() self.stack.append(self.vars[var.name]) self.advance() elif self.current_char() == '^': ch = self.input.read(1) self.stack.append(ord(ch) if ch else -1) self.advance() elif self.current_char() == '.': self.output.write(str(self.stack.pop())) self.advance() else: raise Exception("Invalid character " + self.current_char()) def push_lambda(self): self.advance() res = '' while self.current_char() != ']': res += self.current_char() self.advance() self.advance() self.stack.append(__class__.Lambda(res)) def run_lambda(self, l): lambda_runner = Interpreter(l.code, self.vars, self.stack) lambda_runner.set_input(self.input) lambda_runner.set_output(self.output) lambda_runner.run() def while_loop(self): body = self.stack.pop() cond = self.stack.pop() while True: self.run_lambda(cond) if self.stack.pop() == 0: break else: self.run_lambda(body) def pick(self): i = self.stack.pop() + 1 val = self.stack.pop(-i) self.stack.append(val) def rotate(self): a = self.stack.pop(0) self.stack.append(a) def swap(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(a) self.stack.append(b) def push_num(self): res = 0 while self.current_char() and self.current_char().isdigit(): res = res * 10 + int(self.current_char()) self.advance() self.stack.append(res) def skip_whitespace(self): while self.current_char() and self.current_char().isspace(): self.advance() def skip_comment(self): while self.current_char() != '}': [0][0]#{ self.advance() self.advance() def current_char(self): try: return self.code[self.pos] except: return None def advance(self): self.pos += 1 from io import StringIO def entry(n): interpreter = Interpreter(code) inp = StringIO(str(n)) out = StringIO() interpreter.set_input(inp) interpreter.set_output(out) interpreter.run() return out.getvalue() == '1' [0][0]# If you're reading this you're a cool person :) } |
written by HelloBoi
submitted at
6 likes
1 2 3 4 5 6 | 1m:[[^$1_=~][48-\10*+]#%]y:[$$3ΓΈ$@/@*-]r: 47 ^$z:$$3ΓΈ>\58\>&$p:[48-y;!$h: $1=[0m:]? 2[$2ΓΈ>~m;0=~&][r;!0=$[0m:]?~[\]?]# h;2=$[ 1.]?~[m;.]?]?p;~[z;'X=$[^^^^^'*=$["DWN"]? ~["RGT"]?%%%%]?~[^^^^^'*=$["UPP"]?~["LFT" ]?]?]? |
written by BeatButton
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | const PRIMES: &[u8] = include_bytes!("primes.32b"); // http://www.umopit.ru/CompLab/primes32.htm const NUM_PRIMES: usize = PRIMES.len() / 4; const LAST: u32 = prime_at(NUM_PRIMES - 1); const fn prime_at(index: usize) -> u32 { u32::from_le_bytes([ PRIMES[index * 4], PRIMES[index * 4 + 1], PRIMES[index * 4 + 2], PRIMES[index * 4 + 3], ]) } pub fn entry(num: u32) -> bool { if num < 2 { false } else if num == 2 { true } else if num > LAST { false } else { let mut lo = 0; let mut hi = NUM_PRIMES - 1; let mut isp = false; while lo <= hi { let guess = lo + (hi - lo) / 2; let p = prime_at(guess); use std::cmp::Ordering::*; match num.cmp(&p) { Equal => { isp = true; break; } Less => hi = guess - 1, Greater => lo = guess + 1, } } isp } } |
written by quintopia
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | {Code by SoundOfSpouting#6980 (UID: 151149148639330304)} {This prime tester may randomly call some primes composite for large inputs depending on the FALSE interpreter you use. This is due to integer overflow. In theory, it should correctly label all numbers below 2^16.} [$@$@/@*-]m: 0^[$1+][48-\10*+^]#%$1-[$1&1-$[%2=$["1"]?~["0"]?1_$]?~[ $n:0\1-[$1&1-][\1+\2/]#d:r: 1 0 61 7 2 [$][a:1 d; [$][1-\a;*n;m;!\]# %$$$1=\n;1-=|~& $[ %0\r; [1-$][ \$*n;m;! $n;1-=[@%1_@@]? \ ]# %%$~["0"1_0 0 1_]? ]?~[%]? ]# %["1"1_]? ]? ]?~["0"]? |
written by SoundOfSpouting
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 | // Code by SoundOfSpouting#6980 (UID: 151149148639330304) int entry(int N) { int M=1; for(int L=2;L<N;++L) { M*=L; } return 1-(M+1)%N; } |
written by IFcoltransG
submitted at
4 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | enum Space (Gap => '.', Star => '*', Strudel => '@', Cross => 'X', Naught => 'O'); sub postfix:<space>($_) { Space($_) } sub swap($_) { # swap sides when Strudel { Star } when Star { Strudel } when Cross { Naught } when Naught { Cross } default { Gap } } sub back($_) { when 'd' { 'u' } when 'u' { 'd' } when 'r' { 'l' } when 'l' { 'r' } 'n' } sub infix:<taxi>(@a, @b) { # taxicab distance [+] (@a Z- @b)>>.abs } sub honcho($_) { when Naught { Strudel } when Cross { Star } $_ } class GameBoard { has @.grid is rw; has $.ally is rw; method to-string { "{ $!ally.value }\n" ~ @!grid.deepmap({.value}).map(*.join).join("\n") } method score { my $otal = 0; for @!grid { for @$_ { when Star | Cross { $otal++; } when Strudel | Naught { $otal--; } } } given $!ally { when Naught { $otal } default { -$otal } } } method ally-pos { self.nearest(0, 0){honcho($!ally)} } method enemy-pos { self.nearest(0, 0){honcho(swap($!ally))} } method get($x, $y) { @!grid[$x][$y] } method nearest($x, $y) { my %ashmap; for ^@!grid -> $i { for ^@!grid[$i] -> $j { given %ashmap{ self.get($i, $j) } //= ($i, $j) { # insert into hasmap if unset when (* taxi ($x, $y)) < (($i, $j) taxi ($x, $y)) { # compare distance %ashmap{ self.get($i, $j) } = ($i, $j); } } } } %ashmap } method pathfind($a, $b) { my ($c, $d) = self.ally-pos; when $b > $d { # does horizontal first so more likely to complete boxes as an accident 'r' } when $b < $d { 'l' } when $a > $c { 'd' } when $a < $c { 'u' } 'n' } method pathfind2($a, $b) { my ($c, $d) = self.ally-pos; when $a > $c { 'd' } when $a < $c { 'u' } when $b > $d { 'r' } when $b < $d { 'l' } 'n' } method flow($a, $b) { < rrrrrrrrrrrrrrrrdddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd rrrrrrrrrrrrrrrurrrrrrrrrrrrrrrd ullllllllllllllldlllllllllllllll uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuudddddddddddddddd uuuuuuuuuuuuuuuullllllllllllllll >>>.comb[$a][$b] } method go { if self.score > 1 { # winning when (self.enemy-pos taxi self.ally-pos) %% 2 { 'n' # wait } # go to enemy self.pathfind(|self.enemy-pos) } else { given self.ally-pos { # avoid enemy when (self.enemy-pos taxi *) == 2 { if (self.pathfind(|self.enemy-pos) | self.pathfind2(|self.enemy-pos)) ~~ self.flow(|self.ally-pos) { back(self.flow(|self.ally-pos)) } else { self.flow(|self.ally-pos) } } # get more score # go to good spot self.flow(|$_) } } } } =my plan was look for bits where enemy is making 1-wide path with nothing on either side to ruin all its borders and not get stuck but that was too hard so its only this instead sub MAIN { my $type = (get)space; my @big = lines>>.comb()>>space; my $oard = GameBoard.new(grid => @big, ally => $type); say $oard.go; } # prime time our proto entry(|) {*} subset Tiny of Int where * < 10; multi entry(Tiny $nput) { # known primes <10 $nput ~~ one(2, 3, 5, 7) } subset Small of Int where * < 100; multi entry(Small $nput) { given $nput.comb.tail { when any(0,2...^10) { False } # even numbers when 5 { False } # ends in 5 when $nput.comb.sum ~~ one(1..5) * 3 { False } # multiple of 3 <99 when 1 ^ $nput.comb.head ^ 1 { False } # multiple of 11 >11 when seven($nput) { False } default { True } # no prime factor <sqrt(100) } # <3 } subset Medium of Int where * < 1000000; multi entry(Medium $nput) { when proven-composite($nput) { False } when (given $nput - 1 { factorial($_, $nput) ~~ $_ }) { True } # wilson's theorem } multi entry(Int $_) { when proven-composite($_) { False } default { hard-prime($_) } } our sub proven-composite(Int $_) { # finds easy composite numbers when 1..^100 { !entry($_) } when * % 6 == none(1, 5) { True } # != 1 or -1 mod 6 when !($_ * $_ % 24 ~~ 1) { True } # != 1 mod 24 when * %% (7 | 5) { True } } sub seven(int $nput) { # 7 given -$nput.comb.head(*-1).join + 2 * ($nput % 10) { # double last digit - other digits when 0|7 { True } when -6..13 { False } default { seven(abs($_)) } } } sub factorial(Int $nput is copy, Int $odulus) { my $otal = 1; loop (;$nput > 0;) { $otal %= $odulus; $otal *= $nput--; if !$otal { last; } } $otal % $odulus } our sub hard-prime(int $_) { # trial division $_ <= 1 !|| $_ %% any(2..$_.sqrt) } |
written by SlaveGirlSofia
submitted at
3 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <stdio.h> #include <stdbool.h> // Multiply a and b via long multiplication #define M(a, b) ((long)a * b) % i int entry(int); bool is_multiple_of(int, int, int, int); int main(void) { int i; while (scanf("%d", &i) != -1) printf("%s\n", entry(i) ? "prime" : "composite"); } // returns 1 if i is prime, 0 if it is composite int entry(int i) { // the smallest prime number is 2 if (i < 2) return false; // here are some prime numbers if (i == 2 || i == 3 || i == 5 || i == 7) return true; int am = 0; int logos = i - 1; while ((logos & 1) == 0) { logos >>= 1; am++; } // Check for composite numbers that are multiples of the primes discovered so far // This is valid up until at least 121, a very big number return ( !is_multiple_of(i, am, logos, 2) && !is_multiple_of(i, am, logos, 3) && !is_multiple_of(i, am, logos, 5) && !is_multiple_of(i, am, logos, 7)); } int squizzle(int lo, int i, int hi) { int r = 1; lo %= i; while (hi) { if (hi & 1) r = M(r, lo); lo = M(lo, lo); hi >>= 1; } return r; } bool is_multiple_of(int i, int really, int didnt_obfuscate_this, int be_happy) { int l = i - 1; int o = squizzle(be_happy, i, didnt_obfuscate_this); if (1 == o || o == l) return false; for (int nearly = 1; nearly < really; nearly++) { o = M(o , o); if (l == o || o == l) return false; } return true; } |
written by Olive
submitted at
5 likes
1 | my&entry=&is-prime; |
written by SliceOfArdath
submitted at
4 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | static mut RAIL: Vec<usize> = Vec::new(); static mut TOP: usize = 0; fn raw_brute_prime(p: i32) -> bool { for i in 2..f64::sqrt(p as f64).round() as i32 + 1 { //TST[4] += 1; if p % i == 0 { return false; } } return true; } fn brute_prime(p: usize, lock: usize) -> bool { for i in 2..lock { if p % i == 0 { return false; } } return true; } unsafe fn primeband(n: usize, lock: usize) -> bool { let mut prime_count: usize = 0; let mut e: usize; let mut j: usize; let mut v: Vec<usize> = (2..n+1).collect(); //Lock is TOP bound, sqrt n as usize + 1 //Pass through the band for i in 0..lock { //Early exit with square root. //e not prime = there exits a and b whith axb = e, then a or b are <= sqrt(e). e = v[i]; if e != 0 { prime_count += 1; j = e + i; while j < n - 1 { //bounce from value to value. v[j] = 0; j += e; } } } //railh.reserve(prime_count); RAIL.reserve(prime_count * 2); //By all means not the right amount. for i in 0..n-1 { //All != 0 are primes. e = v[i]; if e != 0 { RAIL.push(e); } } TOP = n; return RAIL.last().unwrap() == &n; //return railh.contains(&n); } unsafe fn extendedprimeband(n: usize, lock: usize) -> bool { //Primeband, but takes in account the already existing prime list. //let bottom; match RAIL.last() { //Nothing to process? Some(i) => {if i >= &n { return false; }}, // else { bottom = *i; } None => return primeband(n, lock), } let mut prime_count: usize = 0; let mut e: usize; let mut j: usize; let mut v: Vec<usize> = (TOP+1..n+1).collect(); //fill the band. values from TOP+1 to n incuded. //let lock = f64::sqrt(n as f64).round() as usize + 1; //TOP bound for calculations; cf primeband. //First pass: the original band. let mut g = 0; e = RAIL[0]; while g < RAIL.len() - 1 && e <= lock { e = RAIL[g]; j = e - (TOP + 1) % e; //sets staring point. //option 2 for setting starting point: (should by all means be slower) /*j = 0; while j < v.len() && (v[j] == 0 || v[j] % e != 0) { j += 1; }*/ while j < v.len() { v[j] = 0; j += e; } g += 1; } //Second pass: extending the band using an adaptation of erathosthene's method //Not exacty sure of how that part works, not going to question it. //g = 0; while g < v.len() && v[g] <= lock //the other option, slower apparently. Again not sure why or how but hey. for i in 0..f64::sqrt(v.len() as f64).round() as usize + 1 { e = v[i]; if e != 0 { prime_count += 1; j = e + i; while j < v.len() { v[j] = 0; j += e; } } } RAIL.reserve(prime_count * 2); //Not enough, but a start. for i in 0..v.len() { //All != 0 are primes. e = v[i]; if e != 0 { RAIL.push(e); } } TOP = n; return RAIL.last().unwrap() == &n; } unsafe fn resolve_band(p: usize, lock: usize) -> bool { //where TOP < p <= TOP * TOP, RAIL not empty. let mut i: usize = 0; let mut e = RAIL[0]; while i < RAIL.len() && e <= lock { e = RAIL[i]; if p == RAIL[i] { return true; } //doubles as a fastcheck. if p % e == 0 { return false; } i += 1; } return true; } /* Not a good tradeoff. unsafe fn fastcheck(p: usize) -> bool { for i in 0..RAIL.len() { if p == RAIL[i] { return true; } if p < RAIL[i] { return false; } } return false; }*/ unsafe fn resolve(p: usize) -> bool { //Damn you and your I32 >:( //assumed that p > 1. let lock = f64::sqrt(p as f64) as usize; if TOP == 0 { return primeband(p, lock); } else if TOP >= lock { return resolve_band(p, lock); } else if TOP <= p * p { return extendedprimeband(lock * 2, f64::sqrt(lock as f64) as usize); } else { //Outside of the scope of this project. return brute_prime(p, lock); } } fn entry(p: i32) -> bool { if p < 2 { return false; } unsafe { return resolve(p as usize); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | use std::time; extern crate rand; use rand::Rng; use std::env; static mut RAIL: Vec<usize> = Vec::new(); static mut TOP: usize = 0; fn raw_brute_prime(p: i32) -> bool { for i in 2..f64::sqrt(p as f64).round() as i32 + 1 { //TST[4] += 1; if p % i == 0 { return false; } } return true; } fn brute_prime(p: usize, lock: usize) -> bool { for i in 2..lock { if p % i == 0 { return false; } } return true; } unsafe fn primeband(n: usize, lock: usize) -> bool { let mut prime_count: usize = 0; let mut e: usize; let mut j: usize; let mut v: Vec<usize> = (2..n+1).collect(); //Lock is TOP bound, sqrt n as usize + 1 //Pass through the band for i in 0..lock { //Early exit with square root. //e not prime = there exits a and b whith axb = e, then a or b are <= sqrt(e). e = v[i]; if e != 0 { prime_count += 1; j = e + i; while j < n - 1 { //bounce from value to value. v[j] = 0; j += e; } } } //railh.reserve(prime_count); RAIL.reserve(prime_count * 2); //By all means not the right amount. for i in 0..n-1 { //All != 0 are primes. e = v[i]; if e != 0 { RAIL.push(e); } } TOP = n; return RAIL.last().unwrap() == &n; //return railh.contains(&n); } unsafe fn extendedprimeband(n: usize, lock: usize) -> bool { //Primeband, but takes in account the already existing prime list. //let bottom; match RAIL.last() { //Nothing to process? Some(i) => {if i >= &n { return false; }}, // else { bottom = *i; } None => return primeband(n, lock), } let mut prime_count: usize = 0; let mut e: usize; let mut j: usize; let mut v: Vec<usize> = (TOP+1..n+1).collect(); //fill the band. values from TOP+1 to n incuded. //let lock = f64::sqrt(n as f64).round() as usize + 1; //TOP bound for calculations; cf primeband. //First pass: the original band. let mut g = 0; e = RAIL[0]; while g < RAIL.len() - 1 && e <= lock { e = RAIL[g]; j = e - (TOP + 1) % e; //sets staring point. //option 2 for setting starting point: (should by all means be slower) /*j = 0; while j < v.len() && (v[j] == 0 || v[j] % e != 0) { j += 1; }*/ while j < v.len() { v[j] = 0; j += e; } g += 1; } //Second pass: extending the band using an adaptation of erathosthene's method //Not exacty sure of how that part works, not going to question it. //g = 0; while g < v.len() && v[g] <= lock //the other option, slower apparently. Again not sure why or how but hey. for i in 0..f64::sqrt(v.len() as f64).round() as usize + 1 { e = v[i]; if e != 0 { prime_count += 1; j = e + i; while j < v.len() { v[j] = 0; j += e; } } } RAIL.reserve(prime_count * 2); //Not enough, but a start. for i in 0..v.len() { //All != 0 are primes. e = v[i]; if e != 0 { RAIL.push(e); } } TOP = n; return RAIL.last().unwrap() == &n; } unsafe fn resolve_band(p: usize, lock: usize) -> bool { //where TOP < p <= TOP * TOP, RAIL not empty. let mut i: usize = 0; let mut e = RAIL[0]; while i < RAIL.len() && e <= lock { e = RAIL[i]; if p == RAIL[i] { return true; } //doubles as a fastcheck. if p % e == 0 { return false; } i += 1; } return true; } /* Not a good tradeoff. unsafe fn fastcheck(p: usize) -> bool { for i in 0..RAIL.len() { if p == RAIL[i] { return true; } if p < RAIL[i] { return false; } } return false; }*/ unsafe fn resolve(p: usize) -> bool { //Damn you and your I32 >:( //assumed that p > 1. let lock = f64::sqrt(p as f64) as usize; if TOP == 0 { return primeband(p, lock); } else if TOP >= lock { return resolve_band(p, lock); } else if TOP <= p * p { return extendedprimeband(lock * 2, f64::sqrt(lock as f64) as usize); } else { //Outside of the scope of this project. return brute_prime(p, lock); } } fn entry(p: i32) -> bool { if p < 2 { return false; } unsafe { return resolve(p as usize); } } fn test_compare(r: i32) { let mut cha: Vec<i32> = Vec::new(); let mut chb: Vec<i32> = Vec::new(); /*for i in 2..r { //assert_eq!(entry(i), raw_brute_prime(i)); if entry(i) != raw_brute_prime(i) { println!("ono {}", i); } }*/ let mut t = time::Instant::now(); for i in 2..r { if entry(i) { cha.push(i); } } let da = time::Instant::now() - t; t = time::Instant::now(); for i in 2..r { if raw_brute_prime(i) { chb.push(i); } } let db = time::Instant::now() - t; for i in 0..cha.len() { if cha[i] != chb[i] { println!("{} {}", cha[i], chb[i]); } } println!("Brute time: {:?} Optimised time: {:?}", db, da); if db<da { println!("Optimised is slower than Brute."); //println!("Optimised is {:?} times slower than Brute.", da / db); } } fn test_self(r: i32) { let t = time::Instant::now(); for i in 2..r { entry(i); } let da = time::Instant::now() - t; println!("Optimised time: {:?}", da); } fn test_actual_compare(r: i32, mx: i32) { let mut cha: Vec<i32> = Vec::new(); let mut chb: Vec<i32> = Vec::new(); let mut rcx: Vec<i32> = Vec::with_capacity(r as usize); let mut rng = rand::thread_rng(); for _ in 2..r { //That way the set is the same rcx.push(rng.gen_range(2, mx)); } let mut t = time::Instant::now(); for i in &rcx { if entry(*i) { cha.push(*i); } } let da = time::Instant::now() - t; t = time::Instant::now(); for i in &rcx { if raw_brute_prime(*i) { chb.push(*i); } } let db = time::Instant::now() - t; println!("Brute time: {:?} Optimised time: {:?}", db, da); if db<da { println!("Optimised is slower than Brute."); } } fn test_actual_self(r: i32, mx: i32) { let mut rng = rand::thread_rng(); let mut rcx: Vec<i32> = Vec::with_capacity(r as usize); for _ in 2..r { //Generate before timing. rcx.push(rng.gen_range(2, mx)); } let t = time::Instant::now(); for i in rcx { entry(i); } let da = time::Instant::now() - t; println!("Optimised time: {:?}", da); } fn test_compare_r(r: i32) { let mut cha: Vec<i32> = Vec::new(); let mut chb: Vec<i32> = Vec::new(); let mut t = time::Instant::now(); for i in 2..r { if entry(r-i+2) { cha.push(r-i+2); } } let da = time::Instant::now() - t; t = time::Instant::now(); for i in 2..r { if raw_brute_prime(r-i+2) { chb.push(r-i+2); } } let db = time::Instant::now() - t; for i in 0..cha.len() { if cha[i] != chb[i] { println!("{} {}", cha[i], chb[i]); } } println!("Brute time: {:?} Optimised time: {:?}", db, da); } fn test_self_r(r: i32) { //let mut cha: Vec<i32> = Vec::new(); let t = time::Instant::now(); for i in 2..r { entry(r-i+2); } let da = time::Instant::now() - t; println!("Optimised time: {:?}", da); } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { println!("This program needs test_mode and range arguments. (int)"); return; } let mode: i32 = args[1].parse().unwrap(); let r: i32 = args[2].parse().unwrap(); if mode == 0 { test_compare(r); } else if mode == 1 { test_self(r); //Should run in under 500 seconds. } else if mode == 2 { if args.len() < 4 { println!("This program needs a max_value argument. (int)"); return; } test_actual_compare(r, args[3].parse().unwrap()); } else if mode == 3 { if args.len() < 4 { println!("This program needs a max_value argument. (int)"); return; } test_actual_self(r, args[3].parse().unwrap()); } else if mode == 4 { test_compare_r(r); } else if mode == 5 { test_self_r(r); } } |
written by LyricLy
submitted at
1 like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | // rustup update // rustup override set nightly #![feature(result_into_ok_or_err)] fn entry < > (x: u32) -> bool { (x.min( 2)..=(x as f64) .sqrt() as u32) .all(|y| x%y != 0) } use std::io::{self, Read}; fn main() { unsafe { #![allow(warnings, arithmetic_overflow)] debug_assert!(false, "must be used in release mode"); let (mut Just, c) = match { use io::stdin; stdin() }.bytes().next() { Some(c) => { let Just = [0; 32*16]; (Just, c.unwrap()) } None => None.unwrap_unchecked() } /* ----------------------------------------- */ ; let _ = io::stdin () .bytes().next() ; /* ----------------------------------------- */ // β follow the reading line β io :: stdin () . read_exact ( &mut Just/*ice*/ ) . unwrap ( ) ; let home = 0-1; let end = 1; let pgup = 0-32; let pgdown = 32; // someme if let Some(me) = Just.iter() .position (| & x|x == c) {; let forwards = [ ("upp", Just[(me+ pgup)%512]), ("lft", Just[(me+ home)%512]), ("rgt", Just[(me+ end)%512]), ("dwn", Just[(me+ pgdown)%512]), ]; let ans = if c == b'X' { [b'@', b'O', b'.'] } else { [b'*', b'X', b'.'] } .iter() .try_for_each(|&c| if let Some((fwd, _)) = { forwards.iter().find(|(_, o)| *o == c)}{; Err(*fwd) } else { Ok(()) }); print!("{}", ans.map(|_| "non").into_ok_or_err()); }}} |
written by razetime
submitted at
3 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include <stdio.h> #include <stdlib.h> #define spit return // (kinky) int mulmod(int a, int b, int mod) { int x = 0, y = a % mod; while (b > 0) { if (b % 2) x = (x + y) % mod; y = (y * 2) % mod; b /= 2; } spit x % mod; } int modulo(int y, int exponent, int mod) { int x = 1; while (exponent > 0) { if (exponent % 2) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } spit x % mod; } int entry(int p) { int i; int s; if (p < 2) spit 0; if (p != 2 && p % 2 == 0) spit 0; s = p - 1; while (s % 2 == 0) s /= 2; for (i = 0; i < p; i++) { int a = rand() % (p - 1) + 1, temp = s; int mod = modulo(a, temp, p); while (temp != p - 1 && mod != 1 && mod != p - 1) { mod = mulmod(mod, mod, p); temp *= 2; } if (mod != p - 1 && temp % 2 == 0) spit 0; } spit 1; } int main() { printf("%i\n", entry(22)); printf("%i\n", entry(23)); spit 0; } |
written by Olivia
submitted at
4 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | from __future__ import division ;print('J') # O((n^2)^(n^2)) primer algorithm # runs very fast for n < 3 # like comment and subscribe for fast algorithms # free tibet import functools, itertools, operator from tqdm import tqdm entry = lambda n: ( lambda Def = lambda x, **s: {setattr(x, n, y) for (n, y) in s.items()}.clear(), new = type('new', (), dict(__getattr__ = lambda _, t: lambda **s: type(t, (), s)) )(): ( lambda op = new.op( __init__ = lambda o, f: Def(o, f=f), __ror__ = lambda o, a: new._( __init__ = lambda o, f, a: Def(o, f=f, a=a), __or__ = lambda o, b: o(o.a, b), __call__ = lambda o, a, b: o.f(a, b), )(o.f, a), ): ( lambda α± = op(pow), α’α’ = op(getattr), α = op(operator.eq), α = op(range), Ξ£ = op( lambda p, a: ( lambda f: (lambda x: f(lambda a: x(x)(a)))(lambda x: f(lambda a: x(x)(a))) )( lambda f: lambda a: (lambda q, w: q if w == 1 else q + f((q, w - 1)))(*a) )((a, p)) ): ( lambda method = new.method(__getattr__ = lambda _, m: op(lambda a, b: (a |α’α’| m)(b)))(), set = new.set( __init__ = lambda S, it, dims=1: ( lambda inner = tuple(it): Def(S, inner=inner, d=dims) )(), __pow__ = lambda S, n: itertools.product(S.inner, repeat=n), __call__ = lambda S, *xs: S.inner[ functools.reduce(lambda a, x: a * round(len(S.inner) |α±| 1 / S.d) + x, xs, 0) ], Each = lambda S, f: {f(e) for e in S.inner}.clear(), quant = lambda S, f: lambda g: f(g(*xs) for xs in S |α±| g.__code__.co_argcount), ): ( lambda quant = method.quant, Each = method.Each: ( lambda quantified = lambda f: op(lambda S, g: (S |quant| f)(g)): ( lambda β±― = quantified(all), Ζ = quantified(any): ( lambda field = lambda S, ε, α§ : ( lambda ε = set(ε, 2), α§ = set( α§ , 2): ( lambda R = set(1 |α| n + 1): ( S |Each| (lambda e: e.Promote(ε, α§ )) or new.structure( __bool__ = lambda _: ( S |β±―| (lambda a, b: a + b == b + a) and S |β±―| (lambda a, b: a * b == b * a) and S |β±―| (lambda a, b, c: (a + b) + c == a + (b + c)) and S |β±―| (lambda a, b, c: (a * b) * c == a * (b * c)) and S |β±―| (lambda a, b, c: a * (b + c) == a * b + a * c) and S |Ζ| (lambda Γ: ( S |Ζ| (lambda π: (Γ != π and S |β±―| (lambda a: a + Γ == a) and S |β±―| (lambda a: a * π == a) and S |β±―| (lambda a: ( S |Ζ| (lambda ο½°a: a + ο½°a == Γ))) and S |β±―| (lambda a: (a == Γ or S |Ζ| (lambda aΜ: a * aΜ == π))) and R |β±―| (lambda p: (p == n) |α| (p |Ξ£| π == Γ)) ))))) )() ) )() )(): ( lambda element = new.element( __init__ = lambda a, i: Def(a, i=i), __add__ = lambda a, b: a.ε(a.i, b.i), __mul__ = lambda a, b: a. α§ (a.i, b.i), Promote = lambda a, ε, α§ : Def(a, ε = ε, α§ = α§ ), ): ( lambda S = set(element(i) for i in 0 |α| n): ( any(tqdm(( field(S, ε, α§ ) for ε in S |α±| (n |α±| 2) for α§ in S |α±| (n |α±| 2) ), unit=" structures", total=(n |α±| 2) |α±| (n |α±| 2))) ) )() )() )() )() )() )() )() )() )() )() |
written by Palaiologos
submitted at
3 likes
written by MattiDragon
submitted at
3 likes
1 | entry = lambda a:not{...for b in range(2,a//2) if a%b==0} |
post a comment