Added prime_factors command
Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
parent
b034158d2f
commit
8f00e6a45a
61
rsa.py
Executable file → Normal file
61
rsa.py
Executable file → Normal file
@ -124,6 +124,9 @@ def main():
|
||||
if sys.argv[1] == "genprime" and len(sys.argv) == 3: #rsa genprime <bits>
|
||||
print(getPrime(int(sys.argv[2])))
|
||||
sys.exit(0)
|
||||
if sys.argv[1] == "prime_factors" and len(sys.argv) == 4: #rsa primefactors <base> <N>
|
||||
prime_factors(sys.argv[3], sys.argv[2])
|
||||
sys.exit(0)
|
||||
if sys.argv[1] == "print" and len(sys.argv) == 3: #rsa print <key>
|
||||
printKey(readKeyFile(sys.argv[2]))
|
||||
sys.exit(0)
|
||||
@ -253,19 +256,8 @@ def verify(cipher_list):
|
||||
else: return None
|
||||
|
||||
def isPrime_cmd(func):
|
||||
number = 0
|
||||
base = 0
|
||||
try:
|
||||
base = int(sys.argv[2])
|
||||
except ValueError as e:
|
||||
print(f'Value {sys.argv[2]} is not a valid base (2, 8, 10, 16)',
|
||||
file=sys.stderr)
|
||||
|
||||
try:
|
||||
number = int(sys.argv[3], base)
|
||||
except ValueError as e:
|
||||
print(f'Value {sys.argv[3]} is not valid for as a base {base} number',
|
||||
file=sys.stderr)
|
||||
|
||||
number = int_base_n_from_str(sys.argv[3], sys.argv[2])
|
||||
|
||||
if func == 0:
|
||||
prime = isPrime(number)
|
||||
@ -274,10 +266,32 @@ def isPrime_cmd(func):
|
||||
|
||||
if prime:
|
||||
print('Prime')
|
||||
print(number)
|
||||
#print(number)
|
||||
else:
|
||||
print('Not prime')
|
||||
|
||||
|
||||
def prime_factors(number, base):
|
||||
|
||||
num = int_base_n_from_str(number, base)
|
||||
factors = {1: 1}
|
||||
k = 0
|
||||
while num % 2 == 0:
|
||||
k += 1
|
||||
num = num / 2
|
||||
if k != 0:
|
||||
factors.update({2: k})
|
||||
|
||||
for i in range(3, int(math.sqrt(num))+1, 2):
|
||||
j = 0
|
||||
while (num % i == 0):
|
||||
j += 1
|
||||
num = num / i
|
||||
if j != 0:
|
||||
factors.update({i: j})
|
||||
if num > 2:
|
||||
factors.update({number: 1})
|
||||
|
||||
print(factors)
|
||||
def readKeyFile(keyName):
|
||||
key = tuple()
|
||||
with open(keysFolder+keyName, "r") as keyFile:
|
||||
@ -408,5 +422,22 @@ def backTrack(x):
|
||||
def keyExist(keyName):
|
||||
exist = os.path.exists(keysFolder+keyName)
|
||||
return exist
|
||||
|
||||
def int_base_n_from_str(st: str, base):
|
||||
|
||||
try:
|
||||
base = int(base)
|
||||
except ValueError as e:
|
||||
print(f'Value {sys.argv[2]} is not a valid base (2, 8, 10, 16)',
|
||||
file=sys.stderr)
|
||||
exit(-1)
|
||||
try:
|
||||
number = int(st, base)
|
||||
except ValueError as e:
|
||||
print(f'Value {sys.argv[3]} is not valid for as a base {base} number',
|
||||
file=sys.stderr)
|
||||
exit(-1)
|
||||
return number
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
Loading…
Reference in New Issue
Block a user