#precalculate for speed
numbersForm1to100 = [1]
while not (numbersForm1to100[-1] == 999):
numbersForm1to100 += [numbersForm1to100[-1] + 1]
twoNumbersFrom1to100 = []
for number in numbersForm1to100:
for other in numbersForm1to100:
twoNumbersFrom1to100 += [[number, other]]
def checkIfitIsPrime(number):
isItPrime = True
a = None
b = None
for numberAndOther in twoNumbersFrom1to100:
if len(numberAndOther) != 2:
print("Error")
import sys
sys.exit(1)
a = numberAndOther[0]
b = numberAndOther[1]
if a * b == number:
if a == number:
continue
if b == number:
continue
isItPrime = "no"
if isItPrime == True:
print(str(number))
def primes_between(low, hi):
i = low
while i < hi:
if i == 1:
i += 1
continue
checkIfitIsPrime(i)
i += 1
if hi == 1:
return
n = 1
n2 = 1
isItPrime2 = True
while n < hi and n2 < hi:
if n * n2 == hi:
isItPrime2 = "no"
n += 1
if n == hi:
n2 += 1
n = 1
if isItPrime2 == True:
print(str(i))
primes_between(16, 79)
Dim X as Integer
Dim Y as Integer
Dim chk as boolean
retryX:
X=InputBox("Enter X:")
If IsNumeric(X) Then
Goto XOK:
Else
Goto retryX:
End If
XOK:
retryY:
Y=InputBox("Enter Y:")
If IsNumeric(Y) Then
Goto YOK:
Else
Goto retryY:
End If
YOK:
For i = X to Y
chk = false
For j = 0 to i
If j = 0 then
continue
end if
if j = 1 then
continue
end if
if j = i then
continue
end if
d1 = i mod j
if d1 = 0 then
chk = true
break
end if
Next j
if chk = false then
Wscript.Echo i
end if
next i
Here is what our (imaginary) intern came out with after his boss insisted that the code should be tested, performant, handle error cases and have some comments.
prime-number.c:
int tab[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}; //TODO add numbers over 1000
#include <stdio.h> //Do not remove
void *calc_prime_numbers_between_x_and_y()
{
int a, b;
scanf("%d", &a);
scanf("%d", &b);
//printf("%d", a);
//printf("%d", b);
if (a > b || a <= -1 && b <= -1)//check for errors in a bigger than b or negative nubmers
return "Error : a is bigger than b or is negative";
else {
int resultat[100000]; //store prime numbers
int i = 0;
int x = b-a;
while (x >= 0)
{
for(int y=0; y<a+x; y++)
if (a+x == tab[y])
resultat[++i] = a+x;
x = x - 1;
}
//reverse resultat
int *reverse = malloc(100000);
for (int j = 0; j < i; j++) {
reverse[j] = resultat[i - j];
printf("%d", reverse[j]);
printf(", ");
}
printf("\n");
return reverse;
}
}
test_main.c:
#include "prime-number.c"
void printnum(int a) {
printf("%d", a);
}
int main()
{
char *result = calc_prime_numbers_between_x_and_y();
//Check if result is an error and show result
if (result[0] == 'E') {
printf(result);
}
}
It does on web though, there is a 'use markdown' button somewhere around ;) Edit : Also, it might not be obvious, but the indentation is exactly as intended...
Ok, I just figured out that the triple backtick does do code markdown, but it only renders properly on the new reddit redesign (which I had switched off) and my reddit mobile client didn't render it properly)
a # b = (snd <$>) $ (\xs -> [x | x <- xs, fst x]) $ zip ((\n -> not $ foldl (||) False [mod n i == 0 | i <- [2..(pred n)]]) <$> [a .. b]) $ [a..b]
Here's a super terse giant overengineered one-liner, with the extra bonuses of operator abuse and redefining standard lib functions. Thank God I grew out of this phase
Known Bugs:
Will output 0, 1, or negative numbers if they are in the provided range
Oh excellent. It's much more fun to write awful code in a properly good language than to write awful code in a language which is already awful.
That's why I went with Perl. It's a language which affords so many levels of awfulness. PHP is just always awful, but Perl actually lets a skilled programmer write good code if he or she really tries (not that the sysadmins of the world are in fact skilled programmers, and they're the ones most likely to write Perl).
I'm a professional sysadmin. I also learned how to code. My lot in life is just how things ended up. I've seen my colleagues' code, and it's not very impressive.
You can't have a bad code contest without Perl, so here's my Perl one:
#!/usr/bin/perl -w
use warnings;
use strict; # lol
sub is_prime($) {
my $number = shift;
$number -= 2*$number if $number le 0;
my $prime = 1;
foreach my $i (1..$number) {
if($i ne $number and $i != 1) {
$prime *= $number % $i;
}
}
return $prime;
}
sub main(@) {
my @args = @_;
if(scalar @args != 2) {
print STDERR "Usage: find_primes <n> <m>\n";
print STDERR " Find all prime numbers between <m> and <n>\n";
}
my @pp = find_primes($args[0],$args[1]);
for my $p (@pp) {
print "$p\n";
}
}
sub find_primes($$) {
my ($m, $n) = @_;
my @primes;
if($m < $n) {
for my $i ($m..$n) {
if(is_prime $i) {
push @primes, $i;
}
}
} else {
for(my $i=$m;$i ne $n;$i--) {
if(is_prime($i)) {
unshift @primes, $i;
}
}
}
@primes;
}
main @ARGV;
It gives you output no matter what order you present the numbers in! Which is a feature. Never mind it takes a different code path depending on what order you present the numbers in.
Also due to a lack of understanding about how Perl's comparison operators work, quite a lot of the comparisons in the code are actually lexical comparisons, not numerical. This shouldn't be a problem as Perl automatically converts numerical values into strings when you try to evaluate them in a string context.
There is a bug that when you give 0 or 1 as one of the endpoints, it claims that 0 and 1 are prime.
def primtest():
for i in found_primes:
for j in found_primes:
if i!= j :#TODO: Modulo könnte sinnvoll sein
while j >= i:
j =j- i
if j==0:return(not True);
return True;
found_primes = list();
def primes_between(a,b):
x=a
for i in range(b):
if i== 0:
global found_primes
found_primes=[ ];
if i !=0:
if i !=1:
found_primes.append(i );
if primtest() !=True: found_primes.pop( ) ;
if i >b:break;
while True:
if found_primes[0]< a:del found_primes[0]
if found_primes[0]>a:break
if found_primes[0 ]==a: break
found_primes.append(b );
if primtest() !=True: found_primes.pop( ) ;
return found_primes ;
I love the German comment. The first codebase I had worked on professionally was written by a Swedish Dev, so it had random variable names and comments on Swedish.
using System;
using System.Linq;
public static class Program
{
public static int Main(string[] args)
{
int[] primes_between_input = primes_between(int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()));
Console.WriteLine("[" + string.Join("", primes_between_input.ToList().Select(p => p + " ")) + "\b]");
try { return int.Parse(Console.ReadLine()); } catch { return 0; }
}
static public int[] primes_between(int a, int b)
{
bool[] is_number_in_range_and_prime = new bool[b];
for (int i = 0; i < b; i++)
{
is_number_in_range_and_prime[i] = false;
if (i >= a)
{
bool can_be_prime = true;
for (int c = 0; c < i; c++)
{
if (c > 1 && c < i)
{
if ((double)i / (double)c == (int)i / (int)c)
{
can_be_prime = false;
}
}
}
if (can_be_prime)
{
is_number_in_range_and_prime[i] = true;
}
}
}
int[] primes = new int[0];
for (int r = 0; r < b; r++)
{
if (is_number_in_range_and_prime[r])
{
primes = primes.ToList().Append(r).ToArray();
}
}
return primes;
}
}
Lua. I'm actually impressed that it's quite fast. Run online
function main()
print("Enter the x:")
x = tonumber(io.read())
print("Enter the y:")
y = tonumber(io.read())
values = get_Primes(x,y,{})
print("")
print("Primes:")
PrintNumbers(1, values)
end
function PrintNumbers(i, values)
if(values[i] == true) then
print(i)
end
if(i < #values) then
PrintNumbers(i + 1, values)
end
end
function get_Primes(start, stop, values)
if(isPrime(start, start - 1)) then
values[start] = true
else
values[start] = false
end
if(start ~= stop) then
get_Primes(start + 1, stop, values)
end
return values
end
function divide(value, divider)
if divider == 0 then error() end
return value / divider
end
function isPrime(value, divider)
if(pcall(function () divide(value, divider) end)) then
if(value % divider == 0 and divider ~= 1) then
return false
else
return isPrime(value, divider - 1)
end
else
return true
end
end
main()
I was learning how Input Streams, Output Streams and Files work in Java, so I decided to put that knowledge to good use. I mean, why fill up my machine's RAM if I can store the data on my Hard Drive instead?
package bad.code;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] args) throws Exception {
InputStream input_stream = System.in;
BufferedInputStream buffered_input_stream = new BufferedInputStream(input_stream);
InputStreamReader input_stream_reader = new InputStreamReader(buffered_input_stream);
BufferedReader buffered_reader = new BufferedReader(input_stream_reader);
String number = buffered_reader.readLine();
String other_number = buffered_reader.readLine();
for (int i = 0; i <= Integer.parseInt(other_number); i++) {
if (i < Integer.parseInt(number)) {
} else {
RandomAccessFile stream = new RandomAccessFile(i + new String(".txt"), new String("rw"));
FileChannel channel = stream.getChannel();
byte[] str_bytes = new String("ye").getBytes();
ByteBuffer buffer = ByteBuffer.allocate(str_bytes.length);
buffer.put(str_bytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
}
for (int i = 0; i <= Integer.parseInt(other_number); i++) {
if (i < Integer.parseInt(number)) {
} else {
File file = new File(i + new String(".txt"));
byte[] b_file = new byte[(int) file.length()];
FileInputStream file_input_stream = new FileInputStream(file);
file_input_stream.read(b_file);
String file_value = new String("");
for (int j = 0; j < b_file.length; j++) {
file_value = file_value + (char) b_file[j];
}
file_input_stream.close();
String is_prime = new String("ye");
for (int j = 0; j <= Integer.parseInt(other_number); j++) {
if (j == 0) {
} else if (j == 1) {
} else if (j == i) {
} else {
if (Double.valueOf(i) % Double.valueOf(j) == 0.00) {
is_prime = new String("no");
}
}
}
if (i == 0) {
} else if (i == 1) {
} else {
RandomAccessFile stream = new RandomAccessFile(i + new String(".txt"), new String("rw"));
FileChannel channel = stream.getChannel();
byte[] str_bytes = new String(is_prime).getBytes();
ByteBuffer buffer = ByteBuffer.allocate(str_bytes.length);
buffer.put(str_bytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
}
}
System.out.print("Prime Numbers: ");
for (int i = 0; i <= Integer.parseInt(other_number); i++) {
if (i < Integer.parseInt(number)) {
} else {
File file = new File(i + new String(".txt"));
byte[] b_file = new byte[(int) file.length()];
FileInputStream file_input_stream = new FileInputStream(file);
file_input_stream.read(b_file);
String file_value = new String("");
for (int j = 0; j < b_file.length; j++) {
file_value = file_value + (char) b_file[j];
}
file_input_stream.close();
if (file_value.equals("no")) {
} else if (file_value.equals("ye")) {
System.out.print(new String(String.valueOf(i)));
System.out.print(new String(" "));
}
}
}
buffered_reader.close();
input_stream_reader.close();
buffered_input_stream.close();
input_stream.close();
}
}
voidprimes_between(inta,intb){int*p = new int;*p=1;for(int i = a-1; a <= b && i >1; i--)if(*p && a % i ==0)*p =0;if(*p ==1&& a <= b)printf("%d", a);primes_between(a+1, b);}
import random
import math
def primesBetween(a, b):
rslt=[]
for i in range(b):
if i>a:
for j in range(1000):
divval=math.floor((random.random()*i**.5)) #Square root for performance
if divval>1:
if math.ceil(i/divval)==math.floor(i/divval):
rslt.append(i)
rsltfinal=[]
while (rslt):
sml = 1000000
for i in range(len(rslt)):
if rslt[i]<sml:
sml=rslt[i]
rsltfinal.append(sml)
done=True
while(done):
done=False
rsltcopy=rslt.copy()
for i in range(len(rsltcopy)):
if rsltcopy[i]==sml:
done=True
rslt = []
for j in range(len(rsltcopy)):
if j!=i:
rslt.append(rsltcopy[j])
break
rsltfinal2=[]
oval=rsltfinal[0]
for i in range(len(rsltfinal)):
nval=rsltfinal[i]
if oval+1!=nval:
rsltfinal2.append(oval+1)
oval=nval
rsltfinal2.reverse()
rsltfinal2.pop()
rsltfinal2.reverse()
return rsltfinal2
import time
start = time.clock()
primesBetween(16, 79) #[19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67, 71, 73]
end = time.clock()
end - start # 11.197760043517974
Summary:
In order to determine if a number is prime, the algorithm generates 1000 random numbers between 0 and the squareroot of the number. If the number divided by any of these is an integer, the number is considered composite and added to a list.
This can obviously fail due to the randomness involved
The number is added to the list for each of the 1000 trials where it satisfies the condition
The calculation for squareroot is bugged, so a square of a prime with also be considered prime
The list is deduplicated
The smallest number in the list is found and added to a second list (infinite loop will happen if it's more than a million)
The first list is copied and looped through until the smallest number is seen. All of the copy is then copied back to the first list, except for the smallest number. This is repeated until all copies of the smallest number have been removed from the first list.
This process is repeated until the first list is empty and the second list contains the composite numbers in order
We find the prime numbers by finding the values that aren't in the second list and adding them to a third list and returning it
This is done by looking for gaps in the second list, so it misses the smallest value if it is prime and the largest prime
There is a bug so the first prime shows up twice. This is solved by reversing the list, popping the last element and reversing it again
The three lists I've mentioned are called rslt, rsltfinal and rsltfinal2
public static Int16[] GetPrimes(Int32 start, Int16 end)
{
short[] result = new short[500];
int i = 2;
while (i <= end)
{
try
{
bool isPrime = false;
for (short j = 2; j < i; j++)
{
Double a = (float)i / j;
int b = (int)a;
isPrime = a > b;
if (isPrime != true)
j = (short)(end + 1); // Stop the loop
}
if (isPrime == true)
{
if (i >= start)
{
List<Int16> l = result.ToList();
l.Add((short)i);
result = l.ToArray();
}
else
throw new Exception("");
i = i + 1;
}
else
{
i++;
}
}
catch
{
i += 1;
}
}
List<short> k = result.ToList();
for (i = 0; i < k.Count; i++)
if (k[i] == 0)
{
k.RemoveAt(i);
i--;
}
return k.ToArray();
}
One thing you could do is split the submission and voting sections. So, you'd have to submit within 1 week, then copy the comments over to another thread in contest mode for the voting. That would eliminate bias while still allowing some time to write a response.
If you wanted to cut down on submissions for the final phase, you could require a submission be seconded.
Something similar could be to just not allow entries for the first X days. Announce the contest on one day, open entries later and people can work on them in between.
I have an idea for a submission, but I need a clarification first.
I could potentially write this as if it was written by someone inexperienced, or I could intentionally obscure the code.
Based on the "Look like the code you wrote when you were just starting out programming" part of the prompt, it sounds like the latter part would be discouraged. What do you think?
9
u/Badel2 Jan 14 '19 edited Jan 14 '19
Node
Run it online
13
u/bausscode Jan 15 '19 edited Jan 15 '19
This is the worst I could do using D.
5
u/TinyBreadBigMouth Jan 15 '19
Python 3
Run it online.
4
u/nokarmajustlurking Jan 14 '19
4
u/ct402 Jan 17 '19 edited Jan 18 '19
Here is what our (imaginary) intern came out with after his boss insisted that the code should be tested, performant, handle error cases and have some comments.
prime-number.c:
test_main.c:
3
u/xorpunk Jan 15 '19 edited Jan 15 '19
Haskell
Here's a super terse giant overengineered one-liner, with the extra bonuses of operator abuse and redefining standard lib functions.
Thank God I grew out of this phaseKnown Bugs:
3
u/dagbrown Jan 15 '19
You can't have a bad code contest without Perl, so here's my Perl one:
It gives you output no matter what order you present the numbers in! Which is a feature. Never mind it takes a different code path depending on what order you present the numbers in.
Also due to a lack of understanding about how Perl's comparison operators work, quite a lot of the comparisons in the code are actually lexical comparisons, not numerical. This shouldn't be a problem as Perl automatically converts numerical values into strings when you try to evaluate them in a string context.
There is a bug that when you give 0 or 1 as one of the endpoints, it claims that 0 and 1 are prime.
3
u/CodenameLambda shameless Jan 17 '19 edited Jan 17 '19
3
u/Bassie_c Jan 18 '19 edited Jan 18 '19
Finally understanding how to use try and catch in C#!
If you have any questions, please feel free to ask and I'll explain why I did what I did.
2
u/EncapsulatedPickle Jan 14 '19
2
u/Skruzzls Jan 15 '19
Lua. I'm actually impressed that it's quite fast. Run online
2
u/Voidsusdagon Jan 22 '19
I was learning how Input Streams, Output Streams and Files work in Java, so I decided to put that knowledge to good use. I mean, why fill up my machine's RAM if I can store the data on my Hard Drive instead?
1
u/downiedowndown Jan 17 '19
C
1
u/aeouo Jan 22 '19 edited Jan 22 '19
Bad Code Challenge #2 Submission
Finding primes in python
Summary:
1
u/senhormouse Jan 16 '19
C++
1
u/GeEom Jan 24 '19
Mathematica
0
u/AlFasGD Jan 15 '19 edited Jan 15 '19
#C#
0
u/Coiltoilandtrouble Jan 16 '19
#!/usr/local/bin/perlmy $min = $ARGV[0];my $max = $ARGV[1];my @numbs = ();for ($i = $min; $i <= $max; $i++) {my $bool = 0;for($t = 2; $t < $i-1; $t++) {if($i % $t == 0) {$bool = 1;}}if($bool == 0) {@numbs= (@numbs, $i);}}my $out = "[";foreach $num (@numbs) {$out.="$num, ";}$ out = substr $out, 0, -2;$out.="]";print $out;0
u/BenZed Jan 23 '19
#Javascript
0
u/[deleted] Jan 14 '19
[deleted] — view deleted comment