Is there a cleaner way to find p*q = n, when p and q are coprime?
Basically trying to write a simple RSA brute force. I have modulus N and I'm trying to find p*q=n where p and q are coprimes.
So far i'm able to find the prime factors of N and I can put them in a list. Then taking that list apart into variables then going through each pair to find coprimes. It's messy, and was wondering if there was a cleaner way of doing it?
my code so far:
from fractions import gcd
import sys
n= 17
print "Modulus (n) = ", n
print("p & q are:")
# While Loop to find prime factors
i=1
list=[]
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
list.append(i)
i=i+1
# takes list of prime factors and splits to variables
for n, val in enumerate(list):
globals()["var%d"%n] = val
# really messy, tries to multiply first 2 variables, if coprime, print the variables
# if no coprime factors move on to next 2 variables
# if no prime factors in the first place, exit
try:
gg0 = gcd(var0,var1)
except:
print "No Prime Factors"
sys.exit()
try:
gg1 = gcd(var1,var2)
if gg1 == True:
print var1, var2
except:
if gg0 == True:
print var0, var1
See also questions close to this topic

Syntax error is not actually an error
I am doing this problem:
Finding Numbers in a Haystack
In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers.
Data Files
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. Sample data: http://py4edata.drchuck.net/regex_sum_42.txt (There are 90 values with a sum=445833)
 Actual data: http://py4edata.drchuck.net/regex_sum_97463.txt (There are 82 values and the sum ends with 873)
These links open in a new window. Make sure to save the file into the same folder as you will be writing your Python program.
Note: Each student will have a distinct data file for the assignment  so only use your own data file for analysis.
I wrote this code:
import re fname = input('Enter a file name: ') try: fhandle = open(fname) except: print ('File cannot be opened:', fname) exit() numlist = list() for line in fhandle: line = line.rstrip() num = re.findall('^New .*: ([09]+)', line) if len(num) > 0: for number in num: number =`enter code here` float(number) numlist.append(number) print (sum(numlist))
it should run, but I get an error at line six at the print statement. I have put a link to the error that comes to screen in the picture. Any advice or solution is greatly appreciated

Yield usage in recursive manner
I was playing around with the
yield
and I made up a function that takes 3 numbers and a limit and computes them in a particular way (the computation is not important, but can be seen in the code below).values = [] def compute(limit, a, b, c): if a <= limit: print("Got {}, {}, {}".format(a, b, c)) values.append([a, b, c]) compute(limit, b*c, a*c, a*b) else: print("Process ended") compute(9999, 2, 3, 4) print(values)
This works, and produces the output:
Got 2, 3, 4 Got 12, 8, 6 Got 48, 72, 96 Got 6912, 4608, 3456 Process ended [[2, 3, 4], [12, 8, 6], [48, 72, 96], [6912, 4608, 3456]]
However, I am sure that this can be done with the usage of
yield
 mainly thevalues
list creation part, which, as you see, is filled manually by me in the function.The reason why I bother at all is just why the
yield
is used in the first place  here it doesn't matter, but what if my task required the 100000th value from this list  constructing it as a whole is not required, or even plainly stupid considering I don't want the previous 99999 values...I tried using something like:
def compute_y(a, b, c): while True: yield b*c, a*c, b*a for a, b, c in compute_y(2, 3, 4): if a > 9999: break
The problem with this is that the numbers in the
for
are the same all the time (2, 3 and 4), so it's never gonna reach other values and because of that it's an infinite loop.tl;dr  can I use yield here at all to make the algorithm more efficient for bigger lists?

Getting the sum of groupby as a new column with distinct values in Pandas
This is how my data look like:
id date rt dnm 101122 20170124 0.0 70 101122 20170108 0.0 49 101122 20170413 0.02976 67 101122 20170803 1.02565 39 101122 20161201 0.0 46 101122 20170125 0.0 69 101122 20170102 0.0 76 101122 20170718 0.02631 38 101122 20160602 0.0 120 221344 20161021 0.00182 176 221344 20160921 0.47732 194 221344 20160623 0.0 169 221344 20171010 0.91391 151 221344 20170429 0.0 33 221344 20170205 0.0 31 221344 20171016 0.0 196 221344 20160925 0.0 33 221344 20160717 0.0 21 221344 20160721 0.0 46 615695 20170712 0.0 21 615695 20170705 0.0 18 615695 20160711 0.0 38 615695 20160719 0.03655 29 615695 20170527 0.0 23 615695 20171222 0.0 20 615695 20170425 0.0 34 615695 20170323 0.0 20 615695 20160923 0.0 25 615695 20160618 0.0 25
I'm trying to get the sum of 'dmn' column for each 'id' and give this new column a name like 'sum_values'. After that I need to get the id's that have the 'sum_values' higher than 300. The following code generates the first part:
data = pd.read_csv(file_name, sep='\t', header=0, parse_dates=[1], infer_datetime_format=True); test = (data.assign(sum_values = data.groupby('id')['dnm'].transform(np.sum)) .query('sum_values > 300'))
This will add a new column named 'sum_values' and repeat the sum value for each id several times. I need to get a unique value of 'id' and 'sum_values' column. But I can't figure out how/where to add the nunique().
This is the desired outcome:
id sum_values(>300) 101122 574 221344 1050
Any ideas?

List<> overwrite value with old list
I have this code:
List<List<string>> strs = new List<List<string>>(); List<string> str = new List<string>(); foreach (DataGridViewRow sr in dataGridView1.SelectedRows) { if(i >= 10) { strs.Add(str); //Here strs have one str with 10 values str.Clear(); i = 0; var a = strs; //Here strs have one str with 0 values } str.Add(sr.Cells["MOBILNI"].Value.ToString().Trim()); i++; } strs.Add(str);
I have list of
strings
which i populate and when it reach 10 members i put whole list into list ofList<string>
, then clear list ofstrings
to populate it with next 10 of items. Problem is that when list ofstrings
reach 10 members, i add it to list ofList<string>
and in debugging i see mystrs
has 1 member (List<string>
) which has 10 elements (10 strings) but when i clear my base list ofstrings
it also clears that list insideList<List<string>>
.When i use
str = new List<string>()
instead ofstr.Clear()
it works normally.So why is this happening and how to overcome it?

ExpandableListView with Search view using Hashmap
I have an expandable listview in my application that contains a list of header data and its child data. I have added a searchview to filter data. While typing in search view, I am getting the filtered data but remaining header also getting displayed. As technical detail, I am using a hashmap of Object and list of objects:HashMap> hashMap
This is my code snippet:
search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { String query = search.getText().toString().toLowerCase(); if(query.isEmpty()  query.length()==0){ adapter = new ScheduleExpandableListViewAdapter(getActivity(), header, childs, hashMap); expandableListView.setAdapter(adapter); expandAll(); } else{ HashMap<ScheduleHeader,List<ScheduleChild>> filteredList = new HashMap<>(); for(ScheduleHeader h:header){ List<ScheduleChild> holdChild = h.getChildrenList(); List<ScheduleChild> newChild = new ArrayList<>(); for(ScheduleChild c:holdChild){ if (c.getTeamName1().toLowerCase().contains(query)  c.getTeamName2().toLowerCase().contains(query)) { newChild.add(c); } } filteredList.put(h,newChild); } adapter = new ScheduleExpandableListViewAdapter(getActivity(), header, childs, filteredList); expandableListView.setAdapter(adapter); expandAll(); } } });
Could anyone help to solve the issue

JSON Lists in Jaspersoft Studio
I have a json file like this:
{ "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] }
and I'm trying to correctly display "cars" array.
I can't use subreports for some reason, so I tryed to configure subDataset according to this link https://community.jaspersoft.com/wiki/listsjaspersoftstudio
But the thing is that child::text() function doesn't work (probably because it assumes XML file) and returns just null.
Is there analogous solution for json files? Couldn't find anything helpful about child::text() function and it's analogues so far :(

Plesk migration comunication problems
I'm trying to use plesk migration extension but it fail suddenly...
With password autentication appear this error
Failed to fetch basic information about resellers, clients and domains data from source servers Cause: Command execution failed on the local server with nonzero exit code. command: rsync r chmod=Fu=r,Du=rwx,go= timeout=30 e 'ssh i /usr/local/psa/var/modules/panelmigrator/sessions/20180521080203/sshkeys/id_rsa.xxxxmyipxxxxxp 27653 o PasswordAuthentication=no o StrictHostKeyChecking=no o GSSAPIAuthentication=no' /usr/local/psa/admin/plib/modules/panelmigrator/backend/lib/python/parallels/plesk/source/legacy/extras/plesk_17_0_pmm_shared/ root@xxxxmyipxxxxx:/tmp/plesk_migratorex8zpzy78niseaodloax8zbi4p08vym3/pmm_agent exit code: 255 stdout: stderr: Permission denied (publickey,gssapikeyex,gssapiwithmic,password). rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.1] That is a critical error, migration was stopped.
With SSH KEY autetication appear this error
Failed to connect to the source server 'source' (xxxxmyipxxxxx) by SSH: not a valid EC private key file
Some info....
Plesk version are the same (Up to date)
SSH Port and Plesk ports are the same and are the default ports
For the ssh key i've follow this guide
and with ssh can comunicate from and to servers in both direction
Os are differents ubuntu for the target and centos for the source
 Private RSA key created without the passphrase
 Follow also this topic without success https://talk.plesk.com/threads/migrationerrorusingsshkeysfailedtoconnecttothesourceserversourcexxxxbyssh.340653/ No particular iptables rules on source server
Thank you in advance.

encrypt and decrypt more than 132 char in Swift
I have this Rsa swift code and it's work good and encrypt or decrepit data but when string.count is more than 132 char error decrepit and encrypt data , how can I decrepit and encrypt data for more than 132 char my Rsa class is, I don't want separate my data
class RSAWrapper { private var publicKey : SecKey? private var privateKey : SecKey? func generateKeyPair(keySize: UInt, privateTag: String, publicTag: String) > Bool { self.publicKey = nil self.privateKey = nil if (keySize != 512 && keySize != 1024 && keySize != 2048) { // Failed print("kelid kharab ast") return false } let publicKeyParameters: [NSString: AnyObject] = [ kSecAttrIsPermanent: true as AnyObject, kSecAttrApplicationTag: publicTag as AnyObject ] let privateKeyParameters: [NSString: AnyObject] = [ kSecAttrIsPermanent: true as AnyObject, kSecAttrApplicationTag: publicTag as AnyObject ] let parameters: [String: AnyObject] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: keySize as AnyObject, kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject, kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject ]; let status : OSStatus = SecKeyGeneratePair(parameters as CFDictionary, &(self.publicKey), &(self.privateKey)) return (status == errSecSuccess && self.publicKey != nil && self.privateKey != nil) } func encrypt(text: String) > [UInt8] { let plainBuffer = [UInt8](text.utf8) var cipherBufferSize : Int = Int(SecKeyGetBlockSize((self.publicKey)!)) var cipherBuffer = [UInt8](repeating:0, count:Int(cipherBufferSize)) // Encrypto should less than key length let status = SecKeyEncrypt((self.publicKey)!, SecPadding.PKCS1, plainBuffer, plainBuffer.count, &cipherBuffer, &cipherBufferSize) if (status != errSecSuccess) { print("Failed Encryption") } return cipherBuffer } func decprypt(encrpted: [UInt8]) > String? { var plaintextBufferSize = Int(SecKeyGetBlockSize((self.privateKey)!)) var plaintextBuffer = [UInt8](repeating:0, count:Int(plaintextBufferSize)) let status = SecKeyDecrypt((self.privateKey)!, SecPadding.PKCS1, encrpted, plaintextBufferSize, &plaintextBuffer, &plaintextBufferSize) if (status != errSecSuccess) { print("Failed Decrypt") return nil } return NSString(bytes: &plaintextBuffer, length: plaintextBufferSize, encoding: String.Encoding.utf8.rawValue)! as String } func encryptBase64(text: String) > String { let plainBuffer = [UInt8](text.utf8) var cipherBufferSize : Int = Int(SecKeyGetBlockSize((self.publicKey)!)) var cipherBuffer = [UInt8](repeating:0, count:Int(cipherBufferSize)) // Encrypto should less than key length let status = SecKeyEncrypt((self.publicKey)!, SecPadding.PKCS1, plainBuffer, plainBuffer.count, &cipherBuffer, &cipherBufferSize) if (status != errSecSuccess) { print("Failed Encryption") } let mudata = NSData(bytes: &cipherBuffer, length: cipherBufferSize) return mudata.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters) } func decpryptBase64(encrpted: String) > String? { let data : NSData = NSData(base64Encoded: encrpted, options: .ignoreUnknownCharacters)! let count = data.length / MemoryLayout<UInt8>.size var array = [UInt8](repeating: 0, count: count) data.getBytes(&array, length:count * MemoryLayout<UInt8>.size) var plaintextBufferSize = Int(SecKeyGetBlockSize((self.privateKey)!)) var plaintextBuffer = [UInt8](repeating:0, count:Int(plaintextBufferSize)) let status = SecKeyDecrypt((self.privateKey)!, SecPadding.PKCS1, array, plaintextBufferSize, &plaintextBuffer, &plaintextBufferSize) if (status != errSecSuccess) { print("Failed Decrypt") return nil } return NSString(bytes: &plaintextBuffer, length: plaintextBufferSize, encoding: String.Encoding.utf8.rawValue)! as String } func getPublicKey() > SecKey? { return self.publicKey } func getPrivateKey() > SecKey? { return self.privateKey }
I try to change UInt8 but when I do that error, what I must to do?

BER decode error
I am doing the RSA signature verify, I will always get this error
terminate called after throwing an instance of 'CryptoPP::BERDecodeErr' what(): BER decode error Aborted (core dumped)
I don't understand why I get this error, I never call the BERDecode before.
This my code segment, I had tried to trace the error it happens in the second line of the code:
FileSource pubFile(publicKey_file.c_str(), true, new HexDecoder); RSASS<PSSR, SHA1>::Verifier pub(pubFile); FileSource signatureFile(sig_file.c_str(), true, new HexDecoder); if (signatureFile.MaxRetrievable() != pub.SignatureLength()) { return false; } SecByteBlock signature(pub.SignatureLength()); signatureFile.Get(signature, signature.size()); bool result = pub.VerifyMessage((const byte*)messages_file.c_str(), messages_file.length(), signature, signature.size()); return result;
I could define what's going wrong, hope to get some help. Thank you.

python big integer multiplication doesn't calculate most significant digits
I have a python program which should multiply 2 big integers.
The problem is I get a different result in java with
BigInteger
class with same input.I have tried DecInt library for python but gives the same answer as using pure python.
Here are my variables:
d = 372049305848826709205673800090501485720867768816
r = 5452188953055713107393819158892374332916586527736541041226026450382
Result I get in python from
d * r
:2028483115341019294875069650745272851135156323450218238187883716036516369477015140871224045070868977706272670887712
Result I get in java with
BigInteger
class:9530687378863294988874153740700860249994095546182028483115341019294875069650745272851135156323450218238187883716036516369477015140871224045070868977706272670887712
Here is my java code:
BigInteger d = new BigInteger("372049305848826709205673800090501485720867768816"); BigInteger r = new BigInteger("5452188953055713107393819158892374332916586527736541041226026450382"); BigInteger tmp1 = d.multiply(r); System.out.println(tmp1);
As you can see, there are some most significant digits that are missed in python's result.
Is there any solution for that?

Producing Strings from Array Multiplication
I am looking to create a javascript function that outputs strings as a result of array multiplication.
The first number of the array will be multiplied by the second, resulting in a string as below.
For ex. when:
console.log(repeatNumbers([[1, 10]])); console.log(repeatNumbers([[1, 2], [2, 3]]));
The result would be:
1111111111 11, 222
I am struggling getting past returning simple multiplication out puts such as 1*10 = 10, and producing a full string (w/o commas) instead.
Any advice would be great  thanks.

cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
I'm making a multiplication practice program. As my title says, if I enter a letter into the console instead of a number, it will run off saying correct on the first one, but incorrect on the rest. Even if you're not touching the keyboard, it'll still spit out incorrect.
ans = table * i; std::cout << table << " * " << i << " =" << std::endl; std::cin >> input; if(input == ans) { std::cout << "Correct! " << ans << std::endl; } else { std::cout << "Incorrect, the answer was " << ans << std::endl; input = 0; ans = 0; } }
Hopefully that gives you a view of what's happening in the code. Here's the output.
Enter the table you'd like to learn. 5 Enter the amount of multiples 3 5 * 0 = s Correct! 0 5 * 1 = Incorrect, the answer was 5 5 * 2 = Incorrect, the answer was 10 5 * 3 = Incorrect, the answer was 15
What could I do to fix this problem? Thanks for your input.

Efficient parallel prime factorization
I am trying to make a parallel version of prime factorization in Java, and have a working program. However, the program is very slow – much slower than my sequential version. I do understand this may have to do with thread optimization and the sheer number of threads (I tried using ExecutorService but I don't think I really got the hang of it). Anyone who can point out a way to optimize this piece of code?
class HovedFaktorArbeider implements Runnable //Class for first step factorization { int fra; int til; int id; List<Long> tempFaktorer; //Must be long since we'll stumble upon primes larger than int.MAX_VALUE accidentally long[] lokaleFaktorer; CyclicBarrier faktorBarrier = new CyclicBarrier(k+1); ExecutorService executorService = Executors.newFixedThreadPool(2); long g; public HovedFaktorArbeider(int fra, int til, int id) { this.fra = fra; this.til = til; this.id = id; } public void run() { try { //int tempK = 2; //Erstatter bare k for aa sjekke long tempN = (long) n; g = (tempN*tempN)100; long tall = g + (long) fra; //The long numbers to be factorized for(int i = fra; i <= til; i++) //For the number split { int tempFra = 0; int tempTil = 0; int rest = 0; int faktor = 0; if(primes.size() % k > 0) //If not perfect division { rest = (primes.size() % k); //Saving remainder faktor = (primes.size()/k); //Saving divisor, spreading remainder rest; //Decrement remainder } else //If perfect divison faktor = primes.size()/k; tempTil = faktor; //Setting end value tempFaktorer = new ArrayList<Long>(); for(int ii = 0; ii < k; ii++) //For the prime number split { //executorService.submit(new HjelpeFaktorArbeider(tempFra, tempTil, tall, ii)); new Thread(new HjelpeFaktorArbeider(tempFra, tempTil, tall, ii)).start(); tempFra = tempTil + 1; //Set new value for start if(rest > 0) { tempTil += faktor + 1; //Spreading remainder rest; } else tempTil += faktor; //New end value } faktorBarrier.await(); lokaleFaktorer = new long[tempFaktorer.size()]; for(int j = 0; j < tempFaktorer.size(); j++) { lokaleFaktorer[j] = tempFaktorer.get(j); } faktorer[i] = lokaleFaktorer; //TNB: i does not start at 0, so placement should be correct tall++; } mainBarrier.await(); executorService.shutdown(); } catch(Exception e){e.printStackTrace();} } public synchronized void oppdaterTempFaktorer(long tall) { tempFaktorer.add(tall); } class HjelpeFaktorArbeider implements Runnable //Class for second step factorization { int fra; int til; int id; long tall; public HjelpeFaktorArbeider(int fra, int til, long tall, int id) { this.fra = fra; this.til = til; this.id = id; this.tall = tall; } public void run() { try { long t = tall; for(int i = fra; i < til; i++) { int primtall = primes.get(i); while(t % primtall == 0) { try { oppdaterTempFaktorer((long) primtall); } catch(Exception e){e.printStackTrace();} t = t/primtall; } } runBarrier.await(); if(t > 1 && id == 0 && !tempFaktorer.contains(t)) { try { oppdaterTempFaktorer(t); } catch(Exception e){e.printStackTrace();} } faktorBarrier.await(); } catch(Exception e){e.printStackTrace();} } } }
As of now, I have a list of primes found through Erastothenes' Sieve, a limit n and cores k (8 on my machine).
P.S.: the reason why there are two Runnable classes, is that I need each and every factorization to be executed by multiple threads.

non negative tensor factorization for very large and very sparse dataset
I am trying to factorize a huge and sparse 3way tensor. The dimensions are 221K x 185K x 61. The # of nonzero elements is around 15M. Is there an open source scaleable library to perform the decomposition and the approximation of such given input tensor? I know here is a tensor toolbox in Matlab but I am not familiar with Matlab and looking for other platforms and languages such as python, java or c++.
Thanks in advance

Better way to find prime factorization of a given number?
I've recently stumbled upon this wonderful site called Project Euler which has a great repository of programming exercises, and am currently working on one where I need to find the largest prime factor of a given number. In this case, the number is 600851475143. Now I've written code that'll find me the prime factorization, but I'm thinking my method might be a little slow. Here is my code:
#include <iostream> #include <limits> #include <vector> using namespace std; bool isPrime(unsigned long long int num) { //See if number is prime for (unsigned long long int divisor = 2; divisor <= num / 2; divisor++) { if (num % divisor == 0) { return false; } } return true; } vector<unsigned long long int> find2Factors(unsigned long long int num) { vector<unsigned long long int> factors; factors.push_back(1); factors.push_back(num); //Multiply numbers to find two random factors for (unsigned long long int i = 2; i <= num / 2; i++) { for (unsigned long long int j = 2; j <= num / 2; j++) { if (i * j == num) { factors.clear(); factors.push_back(i); factors.push_back(j); } } } return factors; } //Recursive helper function for findPrimeFactorization void factorHelper(unsigned long long int num, vector<unsigned long long int> &primeFactors) { if (isPrime(num)) { //Push factor onto vector primeFactors.push_back(num); } else { //Find 2 random factors of num, recurse until primes are reached vector<unsigned long long int> randomFactors = find2Factors(num); factorHelper(randomFactors[0], primeFactors); factorHelper(randomFactors[1], primeFactors); } } //Store all prime factors of num in vector vector<unsigned long long int> findPrimeFactorization(unsigned long long int num) { vector<unsigned long long int> primeFactors; factorHelper(num, primeFactors); return primeFactors; } int main() { unsigned long long int num; cout << "Enter a number to see its prime factorization: "; cin >> num; vector<unsigned long long int> primeFactors(findPrimeFactorization(num)); //Display prime factorization if (primeFactors.size() != 1) { for (unsigned long long int i = 0; i < primeFactors.size(); i++) { if (i != 0) { cout << " x " << primeFactors[i]; } else { cout << primeFactors[i]; } } } else { cout << "1 x " << primeFactors[0]; } cout << endl; return 0; }
Everything is an unsigned long long int because I was lazy and used ints originally, which were too small to hold the number I needed to factorize  so I ctrl+f'ed and replaced all ints. I decided to do this recursively, and I'm not sure if there's an iterative approach that would be faster. I based the program off the primefactortree method of factorization, as that's how I've always done it. In the end, my issue is that when I try and run this program for the given number 600851475143, it takes too long to finish  as in I've had it running for 45 minutes, and it's still churning its merry way down that recursion stack.