Compare commits

...

23 Commits

Author SHA1 Message Date
Nicolás Ortega Froysa
23b8d988e8 Added useful comments. 2019-10-08 18:02:45 +02:00
Nicolás Ortega Froysa
84687f86c1 Using a better algorithm based on property of primes.
I recently found out that `p` being prime, while `p > 3`, then
`p = 6*k (+/-) 1`.
2019-10-08 17:58:08 +02:00
Nicolás Ortega Froysa
2cfc24afb7 Forgot to print 2. 2019-10-08 17:10:39 +02:00
Nicolás Ortega Froysa
d61ef9b034 Entire OpenMPI library is required. 2019-10-08 15:36:33 +02:00
Nicolás Ortega Froysa
23592a98ed Create linked list interface. 2019-09-24 08:20:09 +02:00
Nicolás Ortega Froysa
fadcafaeaf Begin linking to MPI. 2019-09-24 08:19:47 +02:00
Nicolás Ortega Froysa
63e2eda663 Switch to using linked list. 2019-09-24 07:10:12 +02:00
Nicolás Ortega Froysa
d5fb2b06df New objective for v2.0 2019-09-24 07:07:26 +02:00
Nicolás Ortega Froysa
68ac85f3f0 Code refractoring. 2019-09-23 20:44:23 +02:00
Nicolás Ortega Froysa
4d470a14de
Use the MPI compiler. 2018-10-21 10:24:57 +02:00
Nicolás A. Ortega Froysa
874cc75431
Only test up to the sqrt. 2018-10-19 09:05:46 +02:00
Nicolás Ortega Froysa
d2e037e357
Added MPI flags. 2018-10-18 15:26:02 +02:00
Nicolás Ortega Froysa
90158fb04c
Doxygen is no longer in use. 2018-10-18 15:08:29 +02:00
Nicolás Ortega Froysa
bb26ae9b9f
Removed CI file. 2018-10-18 15:07:47 +02:00
Nicolás Ortega Froysa
1b0b8fd443
Removed args.h file. 2018-10-18 15:05:33 +02:00
Nicolás Ortega Froysa
e06e40af3b
Implement verbose option. 2018-10-18 15:05:01 +02:00
Nicolás Ortega Froysa
eaa238a900
Basic prime calculator. 2018-10-18 14:56:15 +02:00
Nicolás Ortega Froysa
bd3181a1a0
Added linked list. 2018-10-18 12:50:57 +02:00
Nicolás Ortega Froysa
89811c1d02
Added new source files. 2018-10-18 12:04:07 +02:00
Nicolás Ortega Froysa
01a32c0e52
Fresh new start. 2018-10-18 12:00:32 +02:00
Nicolás Ortega Froysa
7aceb7fcc7
Remove CMake policy.
The old policy caused issues because it's about to be lost in the newer
versions of CMake, so we'll have to deal with warnings from CMake until
the FindOpenMP.cmake file is updated.
2017-10-03 16:53:34 +02:00
Nicolás Ortega Froysa
3348d52c49
Don't allow writing to the same file. 2017-09-17 05:46:03 +02:00
Nicolás Ortega Froysa
c73bfd1501
Changing BLOCK_SIZE default and allowing override.
The larger BLOCK_SIZE is the less time it has to spend expanding memory,
the faster it gets.
2017-08-03 12:57:34 -05:00
24 changed files with 374 additions and 3228 deletions

9
.gitignore vendored
View File

@ -1,9 +1,6 @@
# Ignore build files
build/*
!build/.keep
# Ignore documentation
doc/
# Ignore binary files
*.o
indivisible
# Ignore vim temporary files
*.sw[a-z]

View File

@ -1,20 +0,0 @@
image: gcc
build:
stage: build
# Install dependencies
before_script:
- apt update && apt -y install cmake libgmp-dev libgomp1
# Build the project
script:
- cd build/
- cmake -DCMAKE_BUILD_TYPE=Release ..
- make
# Find the resulting binary
artifacts:
paths:
- build/indivisible
# Cache .o files for faster compiling
cache:
paths:
- "build/CMakeFiles/indivisible.dir/src/*.o"

View File

@ -1,8 +0,0 @@
Authors
=======
These are a list of people that have contributed to the Uhn project.
| **Name/Alias** | **E-Mail** |
|---------------------------|---------------------------------------|
| Deathsbreed | deathsbreed@themusicinnoise.net |

View File

@ -1,38 +1,42 @@
Change Log
==========
- v0.1: Initial release
- Basic prime calculation.
- Uses a growing vector of known primes and gets the modulus of the number divided by these primes.
- Uses type `long long' to hold prime numbers.
- v0.2: Multi-Precision
- Switch to C.
- Uses GNU Multiple Precision library (GMP) to hold prime numbers, allowing for 'infinite' size.
- Add `likely()' and `unlikely()' macros to optimize.
- v0.2.1: Memory Leak Fixes
- Fixed a major memory leak at the end of the program.
- Added more optimizers.
- v0.3: Optimizations
- Algorithm skips half the known primes.
- Removed `likely()' and `unlikely()' macros due to lack of information.
- Improved performance.
- v0.4: Fixed Algorithm
- Fixed algorithm to actually calculate primes.
- Added extra C99 optimizations.
- v0.5: Minor Changes
- Use `size_t' instead of `unsigned long long int'.
- Minor optimizations to the algorithm.
- Added commandline argument parsing.
- v0.6: User Control
- Allow user to choose base in which the prime numbers are printed.
- Give option for primes to be saved to a file upon exit.
- Free memory and leave instead of emergency exit.
- v0.7: Data Saving
- Allow user to save found primes to be loaded later.
- User can save and read primes in raw output.
- v1.0: Parallelization
- Now completely parallelized.
- Cleaned up/organized the code-base
- Exporting files uses less memory
- Allow searching for the nth prime number
- Clearing some memory leaks
- v0.1: Initial release
- Basic prime calculation.
- Uses a growing vector of known primes and gets the modulus of the number divided by these primes.
- Uses type `long long' to hold prime numbers.
- v0.2: Multi-Precision
- Switch to C.
- Uses GNU Multiple Precision library (GMP) to hold prime numbers, allowing for 'infinite' size.
- Add `likely()' and `unlikely()' macros to optimize.
- v0.2.1: Memory Leak Fixes
- Fixed a major memory leak at the end of the program.
- Added more optimizers.
- v0.3: Optimizations
- Algorithm skips half the known primes.
- Removed `likely()' and `unlikely()' macros due to lack of information.
- Improved performance.
- v0.4: Fixed Algorithm
- Fixed algorithm to actually calculate primes.
- Added extra C99 optimizations.
- v0.5: Minor Changes
- Use `size_t' instead of `unsigned long long int'.
- Minor optimizations to the algorithm.
- Added commandline argument parsing.
- v0.6: User Control
- Allow user to choose base in which the prime numbers are printed.
- Give option for primes to be saved to a file upon exit.
- Free memory and leave instead of emergency exit.
- v0.7: Data Saving
- Allow user to save found primes to be loaded later.
- User can save and read primes in raw output.
- v1.0: Parallelization
- Now completely parallelized.
- Cleaned up/organized the code-base
- Exporting files uses less memory
- Allow searching for the nth prime number
- Clearing some memory leaks
- v2.0: Linked List
- Code cleanup.
- Replace OpenMP code with OpenMPI.
- Use linked list for prime storage.

View File

@ -1,62 +0,0 @@
# Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
# Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
cmake_minimum_required(VERSION 2.6)
project(Indivisible)
cmake_policy(SET CMP0012 OLD)
set(TARGET_NAME indivisible)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "debug")
endif()
string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE)
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
${CMAKE_SOURCE_DIR}/cmake/)
find_package(GMP REQUIRED)
find_package(OpenMP REQUIRED)
include_directories(
${GMP_INCLUDE_DIR})
set(SRCS
src/main.c
src/files.c
src/list.c)
# Define the C flags.
set(CMAKE_C_FLAGS "-std=gnu99 ${OpenMP_C_FLAGS} -Wall -Wextra -Werror -Wfatal-errors -Wmissing-declarations -pedantic-errors")
set(CMAKE_C_FLAGS_DEBUG "-g -O0")
set(CMAKE_C_FLAGS_RELEASE "-O3")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "-g -O3")
set(CMAKE_C_FLAGS_MINSIZEREL "-Os")
if(NOT CMAKE_BUILD_TYPE MATCHES "debug" AND NOT CMAKE_BUILD_TYPE MATCHES "relwithdebinfo")
add_definitions("-DNDEBUG")
endif()
add_executable(${TARGET_NAME} ${SRCS})
target_link_libraries(${TARGET_NAME}
${GMP_LIBRARY})
install(TARGETS ${TARGET_NAME}
RUNTIME DESTINATION "bin")

View File

@ -1,23 +0,0 @@
Contributing
============
We gladly accept contributions to Indivisible (send Git patches to <deathsbreed@themusicinnoise.net>), however there are a few guidelines that must be followed.
1) Copyright & Licensing
------------------------
The copyright of this project and all of its code, unless stated otherwise, belongs to Nicolás Ortega and is licensed with the [GNU GPLv3](/LICENSE). This also applies to all contributions (contributors may add themselves to the [authors file](/AUTHORS.md) for recognition). This is purely for legal purposes, there is no intention to deny your contributions.
2) Documentation
----------------
All new features added must be well documented using DOxygen style comments. If your patch adds a new feature and it is not well documented we will ask you to finish documenting the code before accepting a patch. This is simply so that both the maintainers of this repo and other users can understand the new API that bas been added.
3) Code-Style
-------------
The only aspects that will be religiously upheld for all contributions to this repo are indentation and bracket placement. All indentation must be tab characters (reason being so that everyone can view the code with the indentation that they prefer rather than being forced to see a specific indentation), and brackets must be attached. Everything else is minor and can be overlooked.
Things that would be nice is if you could avoid having the lines being too long, and please avoid having more than one empty line in a row.
4) Fractured Patches
--------------------
Please make sure your patches are fractured into separate parts so that it may be easy for us to deal with them individually. The reason for this is to avoid having patches that both fix bugs and add features when in reality they should be separate requests. The only exception to this will be if the changes made to the code depend on one another to function properly.
If your patch meets all these requirements and is passed by one of the moderators it will be merged into the main repo.

2489
Doxyfile

File diff suppressed because it is too large Load Diff

View File

@ -631,8 +631,8 @@ to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -652,7 +652,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

48
Makefile Normal file
View File

@ -0,0 +1,48 @@
# Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
# Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
CC=mpicc
DEBUG=0
PREFIX=/usr/local
INCFLAGS=
LDFLAGS=-lgmp
DEFS=-DVERSION=\"2.0\" -DAPP_NAME=\"Indivisible\"
CFLAGS=$(INCFLAGS) $(DEFS) -std=c99 -Wall -Wextra -Wfatal-errors -Werror
HDRS=src/globals.h src/llist.h
OBJS=src/llist.o src/main.o src/prime_test.o
ifeq ($(DEBUG),1)
CFLAGS+=-g -O0 -DDEBUG
else
CFLAGS+=-O2 -DNDEBUG
endif
%.o:%.c $(HDRS)
$(CC) -c -o $@ $< $(CFLAGS)
indivisible: $(OBJS)
$(CC) -o $@ $^ $(LDFLAGS)
.PHONY: clean distclean install
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) indivisible
install: indivisible
install -m 755 indivisible $(PREFIX)/bin/

34
README Normal file
View File

@ -0,0 +1,34 @@
===================
*** Indivisible ***
===================
A parallelized prime number generator written in C. It uses a bignum
library as well as OpenMPI for parallelization.
# Building
----------
## Dependencies
The dependencies for compiling are minimal, and should be available
on most UNIX-like systems:
- GNU Make
- GNU Multi-Precision Arithmetics Library (GMP)
- OpenMPI
## Compiling
To compile you simply need to run the `make` command, which will
create the `indivisible` binary file. Additionally you can set the
following flags by appending them to the `make` command:
- `DEBUG=<1|0>`: whether to create a debug or release build. (0 by
default)
- `PREFIX=<path>`: what base prefix to install the binaries at.
(`/usr/local` by default)
# Contributing
--------------
To contribute to the project, please follow the same coding style you
see in the current code base. Then, either submit a pull request or send
a patch file to <nicolas@ortegas.org>.
# License
---------
This project is licensed under the terms & conditions of the GNU General
Public License version 3 or greater (see `LICENSE` file).

View File

@ -1,29 +0,0 @@
Indivisible
===========
[![build status](https://gitlab.com/Deathsbreed/Indivisible/badges/master/build.svg)](https://gitlab.com/Deathsbreed/Indivisible/commits/master)
Indivisible is an optimized prime number generator written in C.
Building
--------
There are multiple dependencies to install before compiling the project:
- CMake
- GMP
- OpenMP
Once the dependencies are installed you can compile by running the following from the root directory of the project:
```bash
$ cd build/
$ cmake ..
$ make
```
To build a release build run `cmake -DCMAKE_BUILD_TYPE=Release ..` instead.
Contributing
------------
If you would like to contribute to Indivisible then please read the [contributing file](/CONTRIBUTING.md) before sending a patch. You may send the patches to <deathsbreed@themusicinnoise.net>.
License
-------
This project is licensed with the [GNU GPLv3](/LICENSE). Since it is an educational project I find it very important that all contributions continue to remain free/libre.

View File

@ -1,3 +0,0 @@
--lineend=linux
--indent=tab
--style=attach

View File

View File

@ -1,24 +0,0 @@
# SOURCE: http://stackoverflow.com/questions/29307862/error-linking-gmp-library
set(GMP_PREFIX "" CACHE PATH "path ")
find_path(GMP_INCLUDE_DIR gmp.h gmpxx.h
PATHS ${GMP_PREFIX}/include /usr/include /usr/local/include )
find_library(GMP_LIBRARY NAMES gmp libgmp
PATHS ${GMP_PREFIX}/lib /usr/lib /usr/local/lib)
if(GMP_INCLUDE_DIR AND GMP_LIBRARY)
get_filename_component(GMP_LIBRARY_DIR ${GMP_LIBRARY} PATH)
set(GMP_FOUND TRUE)
endif()
if(GMP_FOUND)
if(NOT GMP_FIND_QUIETLY)
MESSAGE(STATUS "Found GMP: ${GMP_LIBRARY}")
endif()
else()
if(GMP_FIND_REQUIRED)
message(FATAL_ERROR "Could not find GMP")
endif()
endif()

View File

@ -1,84 +0,0 @@
/*
* Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "files.h"
#include <stdio.h>
#include <gmp.h>
#include <assert.h>
int inputPrimes(char *file, List *list) {
// Assert safeguards
assert(file);
assert(list);
FILE *in = fopen(file, "r");
if(!in) return 1;
mpz_t n;
mpz_init(n);
while(mpz_inp_raw(n, in))
if(addToList(list, n) == 1) return 3;
mpz_clear(n);
if(fclose(in)) return 2;
return 0;
}
int outputPrimes(char *file, List *list, size_t startPos) {
// Assert safeguards
assert(file);
assert(list);
FILE *out = fopen(file, "a");
if(!out) return 1;
printf("Saving primes to `%s'...\n", file);
puts("0%");
for(size_t i = startPos; i < list->end; ++i) {
if(!mpz_out_raw(out, list->list[i])) return 3;
if(i - startPos == (list->end - startPos) / 4) puts("25%");
else if(i - startPos == (list->end - startPos) / 2) puts("50%");
else if(i - startPos == (list->end - startPos) * 3 / 4) puts("75%");
}
puts("100%");
if(fclose(out)) return 2;
return 0;
}
int exportPrimes(char *efile, char *dfile, int base) {
// Assert safeguards
assert(efile);
assert(dfile);
FILE *in = fopen(dfile, "r");
FILE *out = fopen(efile, "w");
if(!in || !out) return 1;
printf("Exporting primes to `%s'...\n", efile);
mpz_t n;
mpz_init(n);
while(mpz_inp_raw(n, in)) {
if(!mpz_out_str(out, base, n)) return 3;
fprintf(out, "\n");
}
if(fclose(in) || fclose(out)) return 2;
return 0;
}

View File

@ -1,57 +0,0 @@
/*
* Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file files.h
* @author Deathsbreed <deathsbreed@themusicinnoise.net>
* @brief Functions to deal with file I/O of primes.
* @details Functions that input, output, and export primes from/to files.
*/
#pragma once
#include "list.h"
/**
* @brief Load primes from an Indivisible file into a List.
* @param file File to input primes from.
* @param list List to load primes into.
* @returns If 0 then load was successful, if 1 then failed to open,
* if 2 failed to close, if 3 failed to allocate new memory to List
* (see `addToList()')
*/
int inputPrimes(char *file, List *list);
/**
* @brief Output primes from a List into an Indivisible file.
* @param file File to output primes to.
* @param list List to read primes from.
* @param startPos The position in the List of primes at which to append
* to the file.
* @returns If 0 then load was successful, if 1 then failed to open,
* if 2 failed to close, if 3 failed when writing.
*/
int outputPrimes(char *file, List *list, size_t startPos);
/**
* @brief Export primes from a List to a plain text file.
* @param efile File to export primes as plain text to.
* @param dfile File to read primes from.
* @param base The base in which the primes will be written.
* @returns If 0 then load was successful, if 1 then failed to open,
* if 2 failed to close, if 3 failed when writing.
*/
int exportPrimes(char *efile, char *dfile, int base);

27
src/globals.h Normal file
View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef APP_NAME
#define APP_NAME "app name"
#endif
#ifndef VERSION
#define VERSION "version"
#endif

View File

@ -1,52 +0,0 @@
/*
* Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "list.h"
#include <stdlib.h>
/**
* This is the number of elements by which the list expands.
*/
#define BLOCK_SIZE 1024
int initList(List *restrict l) {
l->list = malloc(sizeof(mpz_t) * BLOCK_SIZE);
if(!l->list) return 1;
l->size = BLOCK_SIZE;
l->end = 0;
return 0;
}
void deInitList(List *restrict l) {
for(size_t i = 0; i < l->end; ++i) {
mpz_clear(l->list[i]);
}
free(l->list);
}
int addToList(List *restrict l, mpz_t n) {
if(l->end == l->size) {
l->size += BLOCK_SIZE;
void *tmp = realloc(l->list, sizeof(mpz_t) * l->size);
if(!tmp) return 1;
l->list = tmp;
}
mpz_init(l->list[l->end]);
mpz_set(l->list[l->end++], n);
return 0;
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file list.h
* @author Deathsbreed <deathsbreed@themusicinnoise.net>
* @brief Code responsible for List management.
* @details Code responsible for the definition and management of the
* List object.
*/
#pragma once
#include <gmp.h>
/**
* @brief An infinitely expanding list type.
*/
typedef struct {
mpz_t *list; //!< The list of elements
size_t size; //!< How many elements are in the list
size_t end; //!< The last element of the list (in use)
} List;
/**
* @brief Initialize a List.
* @details Initialize the list and its variables, allocating memory
* to the pointer array inside.
* @param[in] l A pointer to a List type to be initialized.
* @returns Returns 0 if successful and 1 if failed.
*/
int initList(List *restrict l);
/**
* @brief Deinitialize a List.
* @details Release all memory that has been allocated to the list.
* @param[in] l A pointer to a List type to be deinitialized.
*/
void deInitList(List *restrict l);
/**
* @brief Adds a new item to a List type.
* @details Add item `n' at the end of a List type.
* @param[out] l List to which the variable should be appended.
* @param[in] n variable to be appended to the list.
* @returns Returns 0 if successful and 1 if failed.
*/
int addToList(List *restrict l, mpz_t n);

61
src/llist.c Normal file
View File

@ -0,0 +1,61 @@
/*
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "llist.h"
#include <stdlib.h>
#include <stdio.h>
void llist_init(struct llist *list) {
list->first = NULL;
list->last = NULL;
list->size = 0;
}
void llist_deinit(struct llist *list) {
struct llist_item *aux = list->first;
while(aux)
{
mpz_clear(aux->n);
struct llist_item *tmp = aux;
aux = aux->next;
free(tmp);
}
}
int llist_insert(struct llist *list, mpz_t n) {
struct llist_item *aux =
malloc(sizeof(struct llist_item));
if(!aux)
{
fprintf(stderr, "ERROR llist_insert(): failed to allocate memory");
return 0;
}
aux->prev = list->last;
aux->next = NULL;
// TODO: check time complexity of these GMP functions
mpz_init(aux->n);
mpz_set(aux->n, n);
if(!list->first)
list->first = aux;
list->last = aux;
list->size++;
return 1;
}

57
src/llist.h Normal file
View File

@ -0,0 +1,57 @@
/*
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <gmp.h>
struct llist_item {
mpz_t n; // the number stored
struct llist_item *next; // the next element in the list
struct llist_item *prev; // the previous element in the list
};
struct llist {
struct llist_item *first; // first element of the list
struct llist_item *last; // last element of the list
size_t size; // number of elements in the list
};
/*
* initialize an empty linked list where `first` and `last` are
* equal to NULL and `size` is 0.
*/
void llist_init(struct llist *list);
/*
* free all space allocated to the list.
*/
void llist_deinit(struct llist *list);
/*
* insert an item at the end of the linked list with value `n`.
*
* returns 1 on success, 0 on failure.
*/
int llist_insert(struct llist *list, mpz_t n);
/*
* insert an item in the linked list in a sorted position.
*
* returns 1 on success, 0 on failure.
*/
int llist_sorted_insert(struct llist *list, mpz_t n);

View File

@ -1,6 +1,6 @@
/*
* Copyright (C) 2017 Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <deathsbreed@themusicinnoise.net>
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -16,291 +16,55 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include "globals.h"
#include "llist.h"
#include "prime_test.h"
#include <signal.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <gmp.h>
#include <omp.h>
#include <sys/stat.h>
int run = 1;
#include "list.h"
#include "files.h"
void quit_signal(int signum) {
printf("Received signal %d. Ending process...\n", signum);
run = 0;
}
#define VERSION "v1.0"
int main() {
printf("%s v%s\n", APP_NAME, VERSION);
static bool run;
signal(SIGINT, quit_signal);
void printUsage(char *progName);
void leave();
mpz_t test_base; // number used to get tested numbers
mpz_t p0, p1; // numbers to be tested for prime-ness.
int main(int argc, char *argv[]) {
// Variables for argument parsing
bool f_help = false,
f_version = false,
f_quiet = false;
int base = 10;
size_t n_prime = 0;
char *dfile = NULL;
char *efile = NULL;
mpz_inits(test_base, p0, p1, NULL);
mpz_set_ui(test_base, 6); // test_base = 6*k
// Parse commandline arguments
int c;
while((c = getopt(argc, argv, "hvqb:f:e:n:")) != -1) {
switch(c) {
case 'h':
f_help = true;
break;
case 'v':
f_version = true;
break;
case 'q':
f_quiet = true;
break;
case 'b':
base = atoi(optarg);
if(base < 2 || base > 62) {
fprintf(stderr,
"Invalid base `%d'. Base must be between 2 and 62.\n",
base);
return 1;
}
break;
case 'f':
dfile = optarg;
break;
case 'e':
efile = optarg;
break;
case 'n':
n_prime = atoi(optarg);
if(n_prime <= 2) {
fprintf(stderr,
"`n' must be larger than 2 (first two primes are 2 and 3).\n");
return 1;
}
break;
default:
printUsage(argv[0]);
return 1;
}
}
puts("2");
puts("3");
// Act based on which flags were used
if(f_help) {
printUsage(argv[0]);
puts("\nArguments:");
puts(" -h print this help information");
puts(" -v print version number of program");
puts(" -q quiet mode");
puts(" -b <base> base in which to print primes between 2 and 62 (default 10)");
puts(" -f <file> file in/from which primes are stored and read from in raw format");
puts(" -e <file> export input file to plain text format");
puts(" -n <n> run until the 'n'th prime\n");
return 0;
} else if(f_version) {
printf("Indivisible %s\n", VERSION);
return 0;
} else if(f_quiet && !dfile) {
puts("Error: you cannot run in quiet mode without specifying a data file.");
printUsage(argv[0]);
return 0;
}
while(run)
{
mpz_sub_ui(p0, test_base, 1); // p0 = test_base - 1
mpz_add_ui(p1, test_base, 1); // p0 = test_base + 1
if(efile && !dfile) {
puts("Error: you must have a file to export to.");
printUsage(argv[0]);
return 0;
} else if(efile && dfile) {
int err = exportPrimes(efile, dfile, base);
if(err) {
if(err == 1) fprintf(stderr, "Error: failed to open files.\n");
else if(err == 2) fprintf(stderr, "Error: failed to close files.\n");
else if(err == 3) fprintf(stderr, "Error: failed to write to export file.\n");
return 1;
}
return 0;
}
if(!omp_get_cancellation()) {
puts("Warning: the OpenMP cancellation environment variable (`OMP_CANCELLATION') is not enabled.");
char in;
while(true) {
printf("[e]nable/[c]ontinue/[q]uit? ");
scanf("%c", &in);
if(in == 'e' || in == 'E') {
putenv("OMP_CANCELLATION=true");
execv(argv[0], argv);
} else if(in == 'c' || in == 'C') {
break;
} else if(in == 'q' || in == 'Q') {
return 0;
}
}
}
// Quit on ^C by setting `run = false'
run = true;
signal(SIGINT, leave);
puts("Use Ctrl+C to exit.");
bool newFile = true;
if(dfile) {
struct stat s;
if(stat(dfile, &s) == 0) newFile = false;
}
// Last position added from file
size_t startPos = 0;
int exitCode = 0;
// Primes we've found
List primes;
if(initList(&primes) == 1) {
fprintf(stderr, "Failed to initialize primes list.\n");
exit(1);
}
// The number we're going to be testing for
mpz_t num;
mpz_init(num);
// Variable for sqrt of `num'
mpz_t numRoot;
mpz_init(numRoot);
// Index of the prime number above and closest to `numRoot'
size_t rootInd = 0;
if(newFile) {
// Add 2, a known prime to this list
mpz_set_ui(num, 2);
if(addToList(&primes, num) == 1) {
fprintf(stderr, "Failed to allocate more memory for list.\n");
exitCode = 1;
goto releaseMemory;
}
// Add 3 as well to optimize the algorithm
mpz_set_ui(num, 3);
if(addToList(&primes, num) == 1) {
fprintf(stderr, "Failed to allocate more memory for list.\n");
exitCode = 1;
goto releaseMemory;
}
if(!f_quiet) {
puts("2\n3");
}
} else {
// Load primes from file
int err = inputPrimes(dfile, &primes);
startPos = primes.end;
if(err == 0) {
printf("Loaded %zu primes.\n", primes.end);
} else {
if(err == 1)
fprintf(stderr, "Failed to open Indivisible file `%s'.\n", dfile);
else if(err == 2)
fprintf(stderr, "Failed to close Indivisible file `%s'.\n", dfile);
else if(err == 3)
fprintf(stderr, "Failed to allocate more memory for list.\n");
exitCode = 1;
goto releaseMemory;
}
/**
* I set to `primes.end-1' because primes.end indicates the next new
* element in the list that can be used, which is also equal to the total
* number of elements in the list.
*/
mpz_set(num, primes.list[primes.end-1]);
}
while(run) {
mpz_add_ui(num, num, 2);
// Calculate the sqrt(num)
mpz_sqrt(numRoot, num);
while(mpz_cmp(primes.list[rootInd], numRoot) <= 0) {
if(++rootInd > primes.end) {
fprintf(stderr, "Error: `rootInd' surpassed `primes.end'.\n");
exitCode = 1;
goto releaseMemory;
}
}
bool isPrime = true;
/**
* Loop through primes we've found until we get to the sqrt of the
* number we're analyzing. Also, skip `2' since we're not testing even
* numbers.
*/
#pragma omp parallel
if(test_prime(p0))
{
#pragma omp for
for(size_t i = 1; i < rootInd; ++i) {
if(mpz_divisible_p(num, primes.list[i])) {
#pragma omp atomic write
isPrime = false;
#pragma omp cancel for
}
#pragma omp cancellation point for
}
mpz_out_str(stdout, 10, p0);
printf("\n");
}
if(test_prime(p1))
{
mpz_out_str(stdout, 10, p1);
printf("\n");
}
if(isPrime) {
// `num' is a prime so we add it to the list and print it
if(addToList(&primes, num) == 1) {
fprintf(stderr, "Failed to allocate more memory for list.\n");
exitCode = 1;
goto releaseMemory;
}
if(!f_quiet) {
if(!mpz_out_str(stdout, base, num))
fprintf(stderr, "Could not print to `stdout'!\n");
printf("\n");
}
}
if(primes.end == n_prime) break;
mpz_add_ui(test_base, test_base, 6); // k += 1
}
mpz_clears(test_base, p0, p1, NULL);
printf("Found %zu primes.\n", primes.end);
if(dfile) {
int err = outputPrimes(dfile, &primes, startPos);
if(err == 0) {
puts("Successfully saved primes.");
} else {
if(err == 1)
fprintf(stderr, "Failed to open/create file `%s'.\n", dfile);
else if(err == 2)
fprintf(stderr, "Failed to close file `%s'.\n", dfile);
else if(err == 3)
fprintf(stderr, "Failed while writing a prime to `%s'.\n", dfile);
exitCode = 1;
goto releaseMemory;
}
}
releaseMemory:
puts("Clearing memory...");
// Clear GMP variables
mpz_clear(numRoot);
mpz_clear(num);
// Deinitialize the list
deInitList(&primes);
puts("Exit successful.");
return exitCode;
return 0;
}
void printUsage(char *progName) {
printf("%s [[-f <file> [-e <file> | -q]] [-b <base>] [-n <n>] | [-h] | [-v]]\n", progName);
}
void leave() { run = false; }

39
src/prime_test.c Normal file
View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "prime_test.h"
int test_prime(const mpz_t p) {
mpz_t psqrt;
mpz_t aux;
mpz_inits(psqrt, aux, NULL);
mpz_sqrt(psqrt, p);
int is_prime = 1;
for(mpz_set_ui(aux, 5); mpz_cmp(aux, psqrt) <= 0; mpz_add_ui(aux, aux, 2))
{
if(mpz_divisible_p(p, aux))
{
is_prime = 0;
break;
}
}
mpz_clears(psqrt, aux, NULL);
return is_prime;
}

27
src/prime_test.h Normal file
View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2019 Ortega Froysa, Nicolás <nicolas@ortegas.org>
* Author: Ortega Froysa, Nicolás <nicolas@ortegas.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <gmp.h>
/*
* checks to see if the number `p` is prime, returning 1 if it is and 0
* if it is not.
*/
int test_prime(const mpz_t p);