Skip to content

Commit

Permalink
new files
Browse files Browse the repository at this point in the history
  • Loading branch information
hearues-zueke-github committed Jun 30, 2022
1 parent 83a81d2 commit c7d9c89
Show file tree
Hide file tree
Showing 16 changed files with 467 additions and 10 deletions.
104 changes: 104 additions & 0 deletions cpp_programs/calculate_prime_numbers.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#include <chrono>
#include <cassert>
#include <fstream>
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

#include "fmt/core.h"
#include "fmt/format.h"
#include "fmt/ranges.h"

using std::accumulate;
using std::fstream;
using std::vector;

using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::nanoseconds;

using fmt::format;
using fmt::print;

using u64 = unsigned long long;

inline u64 sqrt_int(const u64 v_){
u64 v1 = v_ / 2;
u64 v2 = (v1 + v_ / v1) / 2;

for (u64 i = 1; i < 10; i += 1) {
const u64 v3 = (v2 + v_ / v2) / 2;

if (v1 == v3 || v2 == v3) {
break;
}

v1 = v2;
v2 = v3;
}

return v2;
}

int main(int argc, char* argv[]) {
assert((argc >= 3) && "Missing at least one more argument!");

vector<double> l_diff;

const u64 max_p = std::stoi(argv[1]);
const u64 amount = std::stoi(argv[2]);

for (u64 i_round = 0; i_round < amount; ++i_round) {
auto start = high_resolution_clock::now();

vector<u64> l = {2, 3, 5};
const vector<u64> l_jump = {4, 2};

u64 i_jump = 0ull;
u64 p = 7ull;

// const u64 max_p = 1000000ull;

while (p < max_p) {
const u64 max_sqrt_p = sqrt_int(p) + 1;

// is p a prime number? let's test this
bool is_prime = true;
for (u64 i = 0; l[i] < max_sqrt_p; i += 1) {
if (p % l[i] == 0) {
is_prime = false;
break;
}
}

if (is_prime) {
l.push_back(p);
}

p += l_jump[i_jump];
i_jump = (i_jump + 1) % 2;
}

auto finish = high_resolution_clock::now();

double elapsed_time = ((double)duration_cast<nanoseconds>(finish-start).count()) / 1000000000.;
l_diff.push_back(elapsed_time);

if (i_round == 0) {
fstream f(format("/tmp/primes_n_{}_cpp.txt", max_p), std::ios::out);

for (auto v : l) {
f << format("{},", v);
}

f.close();
}
}

double average_time = accumulate(l_diff.begin(), l_diff.end(), 0.) / l_diff.size();

print("l_diff: {}\n", l_diff);
print("average_time: {}\n", average_time);
}
3 changes: 3 additions & 0 deletions nimlang/compile_primes.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#! /bin/bash

nim c --opt:speed -d:release --spellSuggest primes.nim
1 change: 1 addition & 0 deletions nimlang/hello_world.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
echo "Hello World!"
75 changes: 75 additions & 0 deletions nimlang/primes.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import os
import strutils
import streams

import std/strformat
import std/sequtils
import std/times

proc sqrt_int(v: uint64): uint64 =
var v1: uint64 = v div 2
var v2: uint64 = (v1 + v div v1) div 2

for i in 1..10:
let v3 = (v2 + v div v2) div 2

if v1 == v3 or v2 == v3:
break

v1 = v2
v2 = v3

return v2

let args = commandLineParams()
echo(fmt"args: {args}")

let argc = len(args)
assert(argc >= 2, "At least needed 2 arguments!")

let max_p = cast[uint64](parseUInt(args[0]))
let amount = cast[uint64](parseUInt(args[1]))

var l_diff: seq[float64] = @[]
for i_round in 0..amount-1:
let start_time = cpuTime()
var l: seq[uint64]= @[uint64(2), uint64(3), uint64(5)]
var l_jump: seq[uint64]= @[uint64(4), uint64(2)]

var i_jump = uint64(0)
var p = uint64(7)

while p < max_p:
let max_sqrt_p = sqrt_int(p) + 1

# is p a prime number? let's test this
var is_prime = true
var i = uint64(0)
while l[i] < max_sqrt_p:
if p mod l[i] == 0:
is_prime = false
break
i += 1

if is_prime:
l.add(p)

p += l_jump[i_jump]
i_jump = (i_jump + 1) mod 2

let end_time = cpuTime()
let elapsed_time = end_time - start_time
l_diff.add(elapsed_time)

if i_round == 0:
var f = newFileStream(fmt"/tmp/primes_n_{max_p}_nim.txt", FileMode.fmWrite)

for v in l:
f.write(fmt"{v},")

f.close()

let average_time = foldl(l_diff, a + b, float64(0)) / float64(len(l_diff))

echo(fmt"l_diff: {l_diff}")
echo(fmt"average_time: {average_time}")
17 changes: 17 additions & 0 deletions node/test_file_writting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const fs = require('fs');

function main() {
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});

// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there2!');
}

if (require.main === module) {
main();
}
80 changes: 80 additions & 0 deletions primes/calculate_prime_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#! /usr/bin/env -S /usr/bin/time /usr/bin/python3.10

# -*- coding: utf-8 -*-

# Some other needed imports
import datetime
import dill
import gzip
import os
import pdb
import re
import sys
import time
import traceback

import numpy as np
import pandas as pd
import multiprocessing as mp

from collections import defaultdict
from copy import deepcopy, copy
from dotmap import DotMap
from functools import reduce
from hashlib import sha256
from io import BytesIO
from memory_tempfile import MemoryTempfile
from shutil import copyfile
from pprint import pprint
from typing import List, Set, Tuple, Dict, Union, Any
from PIL import Image

CURRENT_WORKING_DIR = os.getcwd()
PATH_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
HOME_DIR = os.path.expanduser("~")
TEMP_DIR = MemoryTempfile().gettempdir()
PYTHON_PROGRAMS_DIR = os.path.join(HOME_DIR, 'git/python_programs')

# set the relative/absolute path where the utils_load_module.py file is placed!
sys.path.append(PYTHON_PROGRAMS_DIR)
from utils_load_module import load_module_dynamically

var_glob = globals()
load_module_dynamically(**dict(var_glob=var_glob, name='utils', path=os.path.join(PYTHON_PROGRAMS_DIR, "utils.py")))
load_module_dynamically(**dict(var_glob=var_glob, name='utils_multiprocessing_manager', path=os.path.join(PYTHON_PROGRAMS_DIR, "utils_multiprocessing_manager.py")))
load_module_dynamically(**dict(var_glob=var_glob, name='prime_numbers_fun', path=os.path.join(PYTHON_PROGRAMS_DIR, "math_numbers/prime_numbers_fun.py")))

mkdirs = utils.mkdirs
MultiprocessingManager = utils_multiprocessing_manager.MultiprocessingManager

get_primes = prime_numbers_fun.get_primes

OBJS_DIR_PATH = os.path.join(PATH_ROOT_DIR, 'objs')
mkdirs(OBJS_DIR_PATH)

PLOTS_DIR_PATH = os.path.join(PATH_ROOT_DIR, 'plots')
mkdirs(PLOTS_DIR_PATH)

if __name__ == '__main__':
n = int(sys.argv[1])
amount = int(sys.argv[2])

l_diff = []

for _ in range(0, amount):
start = time.time()
l = list(get_primes(n=n))
end = time.time()

l_diff.append(end - start)

average_time = sum(l_diff) / len(l_diff)

print(f"l_diff: {l_diff}")
print(f"average_time: {average_time}")

print(f"needed time for n: {n} is {end-start}s")

with open(f"/tmp/primes_n_{n}_py.txt", "w") as f:
for v in l:
f.write(f"{v},")
34 changes: 26 additions & 8 deletions prng/cpp/OwnPRNG.h
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
#pragma once

#include <algorithm>
#include <math.h>
#include <iostream>
#include <numeric>
#include <vector>
#include <cstring>
#include <cassert>

#include "fmt/core.h"
#include "fmt/format.h"
#include "fmt/ranges.h"

namespace OwnPRNG {
#include "sha256.h"

using std::fill;
using std::iota;
using std::vector;
using std::string;
using std::move;

#include "sha256.h"

using fmt::format;
using fmt::print;

Expand Down Expand Up @@ -53,6 +60,7 @@ namespace OwnPRNG {
inline double get_next_double();
void generate_new_values_uint64_t(vector<uint64_t>& vec, const size_t amount);
void generate_new_values_double(vector<double>& vec, const size_t amount);
void generate_new_vec_new_values_double(vector<double>*& vec, const size_t amount);
};

RandomNumberDevice::RandomNumberDevice(const size_t amount, const vector<uint8_t> vec_seed) {
Expand Down Expand Up @@ -236,11 +244,21 @@ namespace OwnPRNG {
void RandomNumberDevice::generate_new_values_double(vector<double>& vec, const size_t amount) {
vec.resize(amount);

vector<uint64_t> vec_uint64_t;
generate_new_values_uint64_t(vec_uint64_t, amount);
// vector<uint64_t> vec_uint64_t;
// generate_new_values_uint64_t(vec_uint64_t, amount);

for (size_t i = 0; i < amount; ++i) {
vec[i] = min_val_double * (vec_uint64_t[i] & mask_uint64_float64);
vec[i] = get_next_double();
// vec[i] = min_val_double * (vec_uint64_t[i] & mask_uint64_float64);
}
}
}
};

void RandomNumberDevice::generate_new_vec_new_values_double(vector<double>*& vec, const size_t amount) {
vec = new vector<double>();
(*vec).resize(amount);

for (size_t i = 0; i < amount; ++i) {
(*vec)[i] = get_next_double();
}
};
};
3 changes: 1 addition & 2 deletions prng/cpp/sha256.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// code from: https://www.programmingalgorithms.com/algorithm/sha256/cpp/
#pragma once

#include <iostream>
#include <string>
#include <stdint.h>

Expand All @@ -26,7 +25,7 @@ class SHA256_CTX {
uint32_t state[8];
};

uint32_t k[64] = {
const uint32_t k[64] = {
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
Expand Down
7 changes: 7 additions & 0 deletions vlang/args.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import os

fn main() {
for i, arg in os.args {
println("i: ${i}, arg: ${arg}")
}
}
11 changes: 11 additions & 0 deletions vlang/call_by_reference.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fn foo(mut a []u64) {
a[0] += 1
}

fn main() {
mut b := []u64{}
print("b.len: ${b.len}")

mut a := [u64(0)]
println("a: ${a}") foo(mut a) println("a: ${a}")
}
Loading

0 comments on commit c7d9c89

Please sign in to comment.