Skip to content

Commit

Permalink
Feat: Fermat factorization algorithm created.
Browse files Browse the repository at this point in the history
  • Loading branch information
Leviathan committed Aug 29, 2024
1 parent ae7be0c commit 7bf0c4e
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.vscode/

bin/

obj/

*.out

*.o
30 changes: 30 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# cc and flags
CC = g++
CXXFLAGS = -std=c++11 -g -Wall
LDFLAGS = -lgmp -lgmpxx
#CXXFLAGS = -std=c++11 -O3 -Wall

# folders
INCLUDE_FOLDER = ./include/
BIN_FOLDER = ./bin/
OBJ_FOLDER = ./obj/
SRC_FOLDER = ./src/

# all sources, objs, and header files
MAIN = Main
TARGET = a.out
SRC = $(wildcard $(SRC_FOLDER)*.cpp)
OBJ = $(patsubst $(SRC_FOLDER)%.cpp, $(OBJ_FOLDER)%.o, $(SRC))

$(shell mkdir -p $(OBJ_FOLDER))

$(shell mkdir -p $(BIN_FOLDER))

$(OBJ_FOLDER)%.o: $(SRC_FOLDER)%.cpp
$(CC) $(CXXFLAGS) -c $< -o $@ -I$(INCLUDE_FOLDER)

all: $(OBJ)
$(CC) $(CXXFLAGS) -o $(BIN_FOLDER)$(TARGET) $(OBJ) ${LDFLAGS}

clean:
@rm -rf $(OBJ_FOLDER)* $(BIN_FOLDER)*
8 changes: 8 additions & 0 deletions include/fermat_factorization.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#ifndef FERMAT_FACTORIZATION
#define FERMAT_FACTORIZATION

#include <gmpxx.h>

mpz_class fermat_factorization(mpz_class n);

#endif
21 changes: 21 additions & 0 deletions src/fermat_factorization.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include "fermat_factorization.hpp"
#include <cmath>

mpz_class fermat_factorization(mpz_class n) {

mpz_class x = std::sqrt(n);

if (x*x == n) return x;


x++; mpz_class y2 = x*x - n;
mpz_class y = std::sqrt(y2);

while (y2 != y*y)
{
y2 += 2*x + 1; x++;
y = std::sqrt(y2);
}

return x + y;
}
8 changes: 8 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include <iostream>
#include "fermat_factorization.hpp"

int main()
{
mpz_class n; std::cin >> n;
std::cout << fermat_factorization(n) << '\n';
}

0 comments on commit 7bf0c4e

Please sign in to comment.