Search Results

Search found 94 results on 4 pages for 'biginteger'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • how to store BigInteger values in oracle database.

    - by Bipul
    I have connected Java program to Oracle database using JDBC. I want to store BigInteger values(512 bits) in the database. What should be the type of the column? I m trying like this: I have taken a column of number type in the database. I converted BigInteger to BigDecimal like this: BigInteger b=new BigInteger("5779857570957802579079"); Number n =b; BigDecimal d=(BigDecimal)n; PreparedStatement pstmt=con.prepareStatemant("insert into database values(?,?)"); pstmt.setString(1,"john"); pstmt.setBigDecimal(2,d); I am getting the following exception: javax.servlet.ServletException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.math.BigDecimal root cause java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.math.BigDecimal Is there anything wrong in this code snippet? If there is, please suggest other methods.

    Read the article

  • Convert arbitrary size of byte[] to BigInteger[] and then safely convert back to exactly the same by

    - by PatlaDJ
    I believe conversion exactly to BigInteger[] would be optimal in my case. Anyone had done or found this written in Java and willing to share? So imagine I have arbitrary size byte[] = {0xff,0x3e,0x12,0x45,0x1d,0x11,0x2a,0x80,0x81,0x45,0x1d,0x11,0x2a,0x80,0x81} How do I convert it to array of BigInteger's and then be able to recover it back the original byte array safely? ty in advance.

    Read the article

  • how to convert BigInteger to String in java

    - by Bipul
    i converted a string to BigInteger as follows: Scanner sc=new Scanner(System.in); System.out.println("enter the message"); String msg=sc.next(); byte[] bytemsg=msg.getBytes(); BigInteger m=new BigInteger(bytemsg); now i want my string back.i m using m.toString() method but not getting desired result. why??? what is bug in it and what is its remedy.

    Read the article

  • BigInteger Library

    A .NET 2.0 library for the 64 bit optimized handling of very large integers, up to 10240 binary digits or approximately (safe to use) 3000 decimal digits

    Read the article

  • Simple RSA encryption (Java)

    - by jake blue
    This is simply for fun. This will not be used for any actual encryption. I'm only first year comp sci student and love cryptography. This took a long time to get working. At approximately N = 18, it begins breaking down. It won't encrypt messages properly after that point. I'm not sure why. Any insights? I'd also appreciate any links you could provide me to tutorials or interesting reading about Cryptography. import java.math.BigInteger; import java.security.SecureRandom; /** * Cryptography. * * Generates public and private keys used in encryption and * decryption * */ public class RSA { private final static BigInteger one = new BigInteger("1"); private final static SecureRandom random = new SecureRandom(); // prime numbers private BigInteger p; private BigInteger q; // modulus private BigInteger n; // totient private BigInteger t; // public key private BigInteger e; // private key private BigInteger d; private String cipherText; /** * Constructor for objects of class RSA */ public RSA(int N) { p = BigInteger.probablePrime(N/2, random); q = BigInteger.probablePrime(N/2, random); // initialising modulus n = p.multiply(q); // initialising t by euclid's totient function (p-1)(q-1) t = (p.subtract(one)).multiply(q.subtract(one)); // initialising public key ~ 65537 is common public key e = new BigInteger("65537"); } public int generatePrivateKey() { d = e.modInverse(t); return d.intValue(); } public String encrypt(String plainText) { String encrypted = ""; int j = 0; for(int i = 0; i < plainText.length(); i++){ char m = plainText.charAt(i); BigInteger bi1 = BigInteger.valueOf(m); BigInteger bi2 = bi1.modPow(e, n); j = bi2.intValue(); m = (char) j; encrypted += m; } cipherText = encrypted; return encrypted; } public String decrypt() { String decrypted = ""; int j = 0; for(int i = 0; i < cipherText.length(); i++){ char c = cipherText.charAt(i); BigInteger bi1 = BigInteger.valueOf(c); BigInteger bi2 = bi1.modPow(d, n); j = bi2.intValue(); c = (char) j; decrypted += c; } return decrypted; } }

    Read the article

  • I am getting a Radix out of range exception on performing decryption

    - by user3672391
    I am generating a keypair and converting one of the same into string which later is inserted into the database using the following code: KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair generatedKeyPair = keyGen.genKeyPair(); PublicKey pubkey = generatedKeyPair.getPublic(); PrivateKey prvkey = generatedKeyPair.getPrivate(); System.out.println("My Public Key>>>>>>>>>>>"+pubkey); System.out.println("My Private Key>>>>>>>>>>>"+prvkey); String keyAsString = new BigInteger(prvkey.getEncoded()).toString(64); I then retrieve the string from the database and convert it back to the original key using the following code (where rst is my ResultSet): String keyAsString = rst.getString("privateKey").toString(); byte[] bytes = new BigInteger(keyAsString, 64).toByteArray(); //byte k[] = "HignDlPs".getBytes(); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA"); PrivateKey privKey = rsaKeyFac.generatePrivate(encodedKeySpec); On using the privKey for RSA decryption, I get the following exception java.lang.NumberFormatException: Radix out of range at java.math.BigInteger.<init>(BigInteger.java:294) at com.util.SimpleFTPClient.downloadFile(SimpleFTPClient.java:176) at com.Action.FileDownload.processRequest(FileDownload.java:64) at com.Action.FileDownload.doGet(FileDownload.java:94) Please guide.

    Read the article

  • Overflow exception while performing parallel factorization using the .NET Task Parallel Library (TPL

    - by Aviad P.
    Hello, I'm trying to write a not so smart factorization program and trying to do it in parallel using TPL. However, after about 15 minutes of running on a core 2 duo machine, I am getting an aggregate exception with an overflow exception inside it. All the entries in the stack trace are part of the .NET framework, the overflow does not come from my code. Any help would be appreciated in figuring out why this happens. Here's the commented code, hopefully it's simple enough to understand: class Program { static List<Tuple<BigInteger, int>> factors = new List<Tuple<BigInteger, int>>(); static void Main(string[] args) { BigInteger theNumber = BigInteger.Parse( "653872562986528347561038675107510176501827650178351386656875178" + "568165317809518359617865178659815012571026531984659218451608845" + "719856107834513527"); Stopwatch sw = new Stopwatch(); bool isComposite = false; sw.Start(); do { /* Print out the number we are currently working on. */ Console.WriteLine(theNumber); /* Find a factor, stop when at least one is found (using the Any operator). */ isComposite = Range(theNumber) .AsParallel() .Any(x => CheckAndStoreFactor(theNumber, x)); /* Of the factors found, take the one with the lowest base. */ var factor = factors.OrderBy(x => x.Item1).First(); Console.WriteLine(factor); /* Divide the number by the factor. */ theNumber = BigInteger.Divide( theNumber, BigInteger.Pow(factor.Item1, factor.Item2)); /* Clear the discovered factors cache, and keep looking. */ factors.Clear(); } while (isComposite); sw.Stop(); Console.WriteLine(isComposite + " " + sw.Elapsed); } static IEnumerable<BigInteger> Range(BigInteger squareOfTarget) { BigInteger two = BigInteger.Parse("2"); BigInteger element = BigInteger.Parse("3"); while (element * element < squareOfTarget) { yield return element; element = BigInteger.Add(element, two); } } static bool CheckAndStoreFactor(BigInteger candidate, BigInteger factor) { BigInteger remainder, dividend = candidate; int exponent = 0; do { dividend = BigInteger.DivRem(dividend, factor, out remainder); if (remainder.IsZero) { exponent++; } } while (remainder.IsZero); if (exponent > 0) { lock (factors) { factors.Add(Tuple.Create(factor, exponent)); } } return exponent > 0; } } Here's the exception thrown: Unhandled Exception: System.AggregateException: One or more errors occurred. --- > System.OverflowException: Arithmetic operation resulted in an overflow. at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey) at System.Linq.Parallel.AnyAllSearchOperator`1.AnyAllSearchOperatorEnumerator`1.MoveNext(Boolean& currentElement, Int32& currentKey) at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork() at System.Linq.Parallel.SpoolingTaskBase.Work() at System.Linq.Parallel.QueryTask.BaseWork(Object unused) at System.Linq.Parallel.QueryTask.<.cctor>b__0(Object o) at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of inner exception stack trace --- at System.Linq.Parallel.QueryTaskGroupState.QueryEnd(Boolean userInitiatedDispose) at System.Linq.Parallel.SpoolingTask.SpoolStopAndGo[TInputOutput,TIgnoreKey](QueryTaskGroupState groupState, PartitionedStream`2 partitions, SynchronousChannel`1[] channels, TaskScheduler taskScheduler) at System.Linq.Parallel.DefaultMergeHelper`2.System.Linq.Parallel.IMergeHelper<TInputOutput>.Execute() at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId) at System.Linq.Parallel.PartitionedStreamMerger`1.Receive[TKey](PartitionedStream`2 partitionedStream) at System.Linq.Parallel.AnyAllSearchOperator`1.WrapPartitionedStream[TKey](PartitionedStream`2 inputStream, IPartitionedStreamRecipient`1 recipient, BooleanpreferStriping, QuerySettings settings) at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive[TKey](PartitionedStream`2 inputStream) at System.Linq.Parallel.ScanQueryOperator`1.ScanEnumerableQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient) at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient) at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings) at System.Linq.Parallel.QueryOpeningEnumerator`1.OpenQuery() at System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext() at System.Linq.Parallel.AnyAllSearchOperator`1.Aggregate() at System.Linq.ParallelEnumerable.Any[TSource](ParallelQuery`1 source, Func`2 predicate) at PFact.Program.Main(String[] args) in d:\myprojects\PFact\PFact\Program.cs:line 34 Any help would be appreciated. Thanks!

    Read the article

  • Project Euler: Programmatic Optimization for Problem 7?

    - by bmucklow
    So I would call myself a fairly novice programmer as I focused mostly on hardware in my schooling and not a lot of Computer Science courses. So I solved Problem 7 of Project Euler: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? I managed to solve this without problem in Java, but when I ran my solution it took 8 and change seconds to run. I was wondering how this could be optimized from a programming standpoint, not a mathematical standpoint. Is the array looping and while statements the main things eating up processing time? And how could this be optimized? Again not looking for a fancy mathematical equation..there are plenty of those in the solution thread. SPOILER My solution is listed below. public class PrimeNumberList { private ArrayList<BigInteger> primesList = new ArrayList<BigInteger>(); public void fillList(int numberOfPrimes) { primesList.add(new BigInteger("2")); primesList.add(new BigInteger("3")); while (primesList.size() < numberOfPrimes){ getNextPrime(); } } private void getNextPrime() { BigInteger lastPrime = primesList.get(primesList.size()-1); BigInteger currentTestNumber = lastPrime; BigInteger modulusResult; boolean prime = false; while(!prime){ prime = true; currentTestNumber = currentTestNumber.add(new BigInteger("2")); for (BigInteger bi : primesList){ modulusResult = currentTestNumber.mod(bi); if (modulusResult.equals(BigInteger.ZERO)){ prime = false; break; } } if(prime){ primesList.add(currentTestNumber); } } } public BigInteger get(int primeTerm) { return primesList.get(primeTerm - 1); } }

    Read the article

  • Generating exactly prime number with Java

    - by Viet
    Hi, I'm aware of the function BigInteger.probablePrime(int bitLength, Random rnd) that outputs probably prime number of any bit length. I want a REAL prime number in Java. Is there any FOSS library to do so with acceptable performance? Thanks in advance!

    Read the article

  • Handling "Big" Integers in C#

    - by priyanka.sarkar
    How do I handle big integers in C#? I have a function that will give me the product of divisors: private static int GetDivisorProduct(int N, int product) { for (int i = 1; i < N; i++) { if (N % i == 0) { Console.WriteLine(i.ToString()); product *= i; } } return product; } The calling function is GetDivisorProduct(N, 1) If the result is bigger than 4 digits , I should obtain only the last 4 digits. ( E.g. If I give an input of 957, the output is 7493 after trimming out only the last four values. The actual result is 876467493.). Other sample inputs: If I give 10000, the output is 0. The BigInteger class has been removed from the C# library! How can I get the last four digits?

    Read the article

  • BitShifting with BigIntegers in Java

    - by ThePinkPoo
    I am implementing DES Encryption in Java with use of BigIntegers. I am left shifting binary keys with Java BigIntegers by doing the BigInteger.leftShift(int n) method. Key of N (Kn) is dependent on the result of the shift of Kn-1. The problem I am getting is that I am printing out the results after each key is generated and the shifting is not the expected out put. The key is split in 2 Cn and Dn (left and right respectively). I am specifically attempting this: "To do a left shift, move each bit one place to the left, except for the first bit, which is cycled to the end of the block. " It seems to tack on O's on the end depending on the shift. Not sure how to go about correcting this. Results: c0: 11110101010100110011000011110 d0: 11110001111001100110101010100 c1: 111101010101001100110000111100 d1: 111100011110011001101010101000 c2: 11110101010100110011000011110000 d2: 11110001111001100110101010100000 c3: 1111010101010011001100001111000000 d3: 1111000111100110011010101010000000 c4: 111101010101001100110000111100000000 d4: 111100011110011001101010101000000000 c5: 11110101010100110011000011110000000000 d5: 11110001111001100110101010100000000000 c6: 1111010101010011001100001111000000000000 d6: 1111000111100110011010101010000000000000 c7: 111101010101001100110000111100000000000000 d7: 111100011110011001101010101000000000000000 c8: 1111010101010011001100001111000000000000000 d8: 1111000111100110011010101010000000000000000 c9: 111101010101001100110000111100000000000000000 d9: 111100011110011001101010101000000000000000000 c10: 11110101010100110011000011110000000000000000000 d10: 11110001111001100110101010100000000000000000000 c11: 1111010101010011001100001111000000000000000000000 d11: 1111000111100110011010101010000000000000000000000 c12: 111101010101001100110000111100000000000000000000000 d12: 111100011110011001101010101000000000000000000000000 c13: 11110101010100110011000011110000000000000000000000000 d13: 11110001111001100110101010100000000000000000000000000 c14: 1111010101010011001100001111000000000000000000000000000 d14: 1111000111100110011010101010000000000000000000000000000 c15: 11110101010100110011000011110000000000000000000000000000 d15: 11110001111001100110101010100000000000000000000000000000

    Read the article

  • The best cross platform (portable) arbitrary precision math library

    - by Siu Ching Pong - Asuka Kenji
    Dear ninjas / hackers / wizards, I'm looking for a good arbitrary precision math library in C or C++. Could you please give me some advices / suggestions? The primary requirements: It MUST handle arbitrarily big integers (my primary interest is on integers). In case that you don't know what the word arbitrarily big means, imagine something like 100000! (the factorial of 100000). The precision MUST NOT NEED to be specified during library initialization / object creation. The precision should ONLY be constrained by the available resources of the system. It SHOULD utilize the full power of the platform, and should handle "small" numbers natively. That means on a 64-bit platform, calculating 2^33 + 2^32 should use the available 64-bit CPU instructions. The library SHOULD NOT calculate this in the same way as it does with 2^66 + 2^65 on the same platform. It MUST handle addition (+), subtraction (-), multiplication (*), integer division (/), remainder (%), power (**), increment (++), decrement (--), gcd(), factorial(), and other common integer arithmetic calculations efficiently. Ability to handle functions like sqrt() (square root), log() (logarithm) that do not produce integer results is a plus. Ability to handle symbolic computations is even better. Here are what I found so far: Java's BigInteger and BigDecimal class: I have been using these so far. I have read the source code, but I don't understand the math underneath. It may be based on theories / algorithms that I have never learnt. The built-in integer type or in core libraries of bc / Python / Ruby / Haskell / Lisp / Erlang / OCaml / PHP / some other languages: I have ever used some of these, but I have no idea on which library they are using, or which kind of implementation they are using. What I have already known: Using a char as a decimal digit, and a char* as a decimal string and do calculations on the digits using a for-loop. Using an int (or a long int, or a long long) as a basic "unit" and an array of it as an arbitrary long integer, and do calculations on the elements using a for-loop. Booth's multiplication algorithm What I don't know: Printing the binary array mentioned above in decimal without using naive methods. Example of a naive method: (1) add the bits from the lowest to the highest: 1, 2, 4, 8, 16, 32, ... (2) use a char* string mentioned above to store the intermediate decimal results). What I appreciate: Good comparisons on GMP, MPFR, decNumber (or other libraries that are good in your opinion). Good suggestions on books / articles that I should read. For example, an illustration with figures on how a un-naive arbitrarily long binary to decimal conversion algorithm works is good. Any help. Please DO NOT answer this question if: you think using a double (or a long double, or a long long double) can solve this problem easily. If you do think so, it means that you don't understand the issue under discussion. you have no experience on arbitrary precision mathematics. Thank you in advance! Asuka Kenji

    Read the article

  • XSLT big integer (int64) handling msxml

    - by Farid Z
    When trying to do math on an big integer (int64) large number in xslt template I get the wrong result since there is no native 64-bit integer support in xslt (xslt number is 64-bit double). I am using msxml 6.0 on Windows XP SP3. Are there any work around for this on Windows? <tables> <table> <table_schem>REPADMIN</table_schem> <table_name>TEST_DESCEND_IDENTITY_BIGINT</table_name> <column> <col_name>COL1</col_name> <identity> <col_min_val>9223372036854775805</col_min_val> <col_max_val>9223372036854775805</col_max_val> <autoincrementvalue>9223372036854775807</autoincrementvalue> <autoincrementstart>9223372036854775807</autoincrementstart> <autoincrementinc>-1</autoincrementinc> </identity> </column> </table> </tables> This test returns true due to overflow (I am assuming) but actually is false if I could tell the xslt processor somehow to use int64 rather than the default 64-bit double for the data since big integer is the actual data type for the numbers in the xml input. <xsl:when test="autoincrementvalue = (col_min_val + autoincrementinc)"> <xsl:value-of select="''"/> </xsl:when> here is the complete template <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <!--Reseed Derby identity column--> <xsl:output omit-xml-declaration='yes' method='text' /> <xsl:param name="stmtsep">;</xsl:param> <xsl:param name="schemprefix"></xsl:param> <xsl:template match="tables"> <xsl:variable name="identitycount" select="count(table/column/identity)"></xsl:variable> <xsl:for-each select="table/column/identity"> <xsl:variable name="table_schem" select="../../table_schem"></xsl:variable> <xsl:variable name="table_name" select="../../table_name"></xsl:variable> <xsl:variable name="tablespec"> <xsl:if test="$schemprefix"> <xsl:value-of select="$table_schem"/>.</xsl:if><xsl:value-of select="$table_name"/></xsl:variable> <xsl:variable name="col_name" select="../col_name"></xsl:variable> <xsl:variable name="newstart"> <xsl:choose> <xsl:when test="autoincrementinc > 0"> <xsl:choose> <xsl:when test="col_max_val = '' and autoincrementvalue = autoincrementstart"> <xsl:value-of select="''"/> </xsl:when> <xsl:when test="col_max_val = ''"> <xsl:value-of select="autoincrementstart"/> </xsl:when> <xsl:when test="autoincrementvalue = (col_max_val + autoincrementinc)"> <xsl:value-of select="''"/> </xsl:when> <xsl:when test="(col_max_val + autoincrementinc) &lt; autoincrementstart"> <xsl:value-of select="autoincrementstart"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="col_max_val + autoincrementinc"/> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:when test="autoincrementinc &lt; 0"> <xsl:choose> <xsl:when test="col_min_val = '' and autoincrementvalue = autoincrementstart"> <xsl:value-of select="''"/> </xsl:when> <xsl:when test="col_min_val = ''"> <xsl:value-of select="autoincrementstart"/> </xsl:when> <xsl:when test="autoincrementvalue = (col_min_val + autoincrementinc)"> <xsl:value-of select="''"/> </xsl:when> <xsl:when test="(col_min_val + autoincrementinc) > autoincrementstart"> <xsl:value-of select="autoincrementstart"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="col_min_val + autoincrementinc"/> </xsl:otherwise> </xsl:choose> </xsl:when> </xsl:choose> </xsl:variable> <xsl:if test="not(position()=1)"><xsl:text> </xsl:text></xsl:if> <xsl:choose> <!--restart with ddl changes both the next identity value AUTOINCREMENTVALUE and the identity start number AUTOINCREMENTSTART eventhough in this casewe only want to change only the next identity number--> <xsl:when test="$newstart != '' and $newstart != autoincrementvalue">alter table <xsl:value-of select="$tablespec"/> alter column <xsl:value-of select="$col_name"/> restart with <xsl:value-of select="$newstart"/><xsl:if test="$identitycount>1">;</xsl:if></xsl:when> <xsl:otherwise>-- reseed <xsl:value-of select="$tablespec"/> is not necessary</xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:template> </xsl:stylesheet>

    Read the article

  • Pros and cons of ways of storing an unsigned int without an unsigned int data type

    - by fields
    I have values that are 64-bit unsigned ints, and I need to store them in mongodb, which has no unsigned int type. I see three main possibilities for storing them in other field types, and converting on going in and out: Using a signed int is probably easiest and most space efficient, but has the disadvantage that they're not human readable and if someone forgets to do the conversion, some of them will work, which may obscure errors. Raw binary is probably most difficult for inexperienced programmers to deal with, and also suffers from non-human-readability. A string representation is the least space efficient (~40 bytes in unicode vs 8 bytes per field), but then at least all of the possible values will map properly, and for querying only a conversion to string is required instead of a more complicated conversion. I need these values to be available from different platforms, so a single driver-specific solution isn't an option. Any major pros and cons I've missed? Which one would you use?

    Read the article

  • Arbitrary-precision arithmetic Explanation

    - by TT
    I'm trying to learn C and have come across the inability to work with REALLY big numbers (i.e., 100 digits, 1000 digits, etc.). I am aware that there exist libraries to do this, but I want to attempt to implement it myself. I just want to know if anyone has or can provide a very detailed, dumbed down explanation of arbitrary-precision arithmetic. Thanks!

    Read the article

  • What data stucture should I use for BigInt class

    - by user1086004
    I would like to implement a BigInt class which will be able to handle really big numbers. I want only to add and multiply numbers, however the class should also handle negative numbers. I wanted to represent the number as a string, but there is a big overhead with converting string to int and back for adding. I want to implement addition as on the high school, add corresponding order and if the result is bigger than 10, add the carry to next order. Then I thought that it would be better to handle it as a array of unsigned long long int and keep the sign separated by bool. With this I'm afraid of size of the int, as C++ standard as far as I know guarantees only that int < float < double. Correct me if I'm wrong. So when I reach some number I should move in array forward and start adding number to the next array position. Is there any data structure that is appropriate or better for this? Thanks in advance.

    Read the article

  • C++ converting hexadecimal md5 hash to decimal integer

    - by Zackery
    I'm doing Elgamal Signature Scheme and I need to use the decimal hash value from the message to compute S for signature generation. string hash = md5(message); cout << hash << endl; NTL::ZZ msgHash = strtol(hash.c_str(), NULL, 16); cout << msgHash << endl; There are no integer large enough to contain the value of 32 byte hexadecimal hash, and so I tried big integer from NTL library but it didn't work out because you cannot assign long integer to NTL::ZZ type. Is there any good solution to this? I'm doing this with visual C++ in Visual Studio 2013.

    Read the article

  • Why doesn't my processor have built-in BigInt support?

    - by ol
    As far as I understood it, BigInts are usually implemented in most programming languages as strings containing numbers, where, eg.: when adding two of them, each digit is added one after another like we know it from school, e.g.: 246 816 * * ---- 1062 Where * marks that there was an overflow. I learned it this way at school and all BigInt adding functions I've implemented work similar to the example above. So we all know that our processors can only natively manage ints from 0 to 2^32 / 2^64. That means that most scripting languages in order to be high-level and offer arithmetics with big integers, have to implement/use BigInt libraries that work with integers as strings like above. But of course this means that they'll be far slower than the processor. So what I've asked myself is: Why doesn't my processor have a built-in BigInt function? It would work like any other BigInt library, only (a lot) faster and at a lower level: Processor fetches one digit from the cache/RAM, adds it, and writes the result back again. Seems like a fine idea to me, so why isn't there something like that?

    Read the article

  • Diffie-Hellman -- Primitive root mod n -- cryptography question.

    - by somewhat confused
    In the below snippet, please explain starting with the first "for" loop what is happening and why. Why is 0 added, why is 1 added in the second loop. What is going on in the "if" statement under bigi. Finally explain the modPow method. Thank you in advance for meaningful replies. public static boolean isPrimitive(BigInteger m, BigInteger n) { BigInteger bigi, vectorint; Vector<BigInteger> v = new Vector<BigInteger>(m.intValue()); int i; for (i=0;i<m.intValue();i++) v.add(new BigInteger("0")); for (i=1;i<m.intValue();i++) { bigi = new BigInteger("" + i); if (m.gcd(bigi).intValue() == 1) v.setElementAt(new BigInteger("1"), n.modPow(bigi,m).intValue()); } for (i=0;i<m.intValue();i++) { bigi = new BigInteger("" + i); if (m.gcd(bigi).intValue() == 1) { vectorint = v.elementAt(bigi.intValue()); if ( vectorint.intValue() == 0) i = m.intValue() + 1; } } if (i == m.intValue() + 2) return false; else return true; }

    Read the article

  • why is a minus sign prepended to my biginteger?

    - by kyrogue
    package ewa; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; import java.math.BigInteger; /** * * @author Lotus */ public class md5Hash { public static void main(String[] args) throws NoSuchAlgorithmException { String test = "abc"; MessageDigest md = MessageDigest.getInstance("MD5"); try { md.update(test.getBytes("UTF-8")); byte[] result = md.digest(); BigInteger bi = new BigInteger(result); String hex = bi.toString(16); System.out.println("Pringting result"); System.out.println(hex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(md5Hash.class.getName()).log(Level.SEVERE, null, ex); } } } i am testing conversion of byte to hex and when done, the end result has a minus sign on the beginning of the string, why does this happen? i have read the docs and it says it will add a minus sign, however i do not understand it. And will the minus sign affect the hash result? because i am going to implement it to hash password stored on my database

    Read the article

  • Saturated addition of two signed Java 'long' values

    - by finnw
    How can one add two long values (call them x and y) in Java so that if the result overflows then it is clamped to the range Long.MIN_VALUE..Long.MAX_VALUE? For adding ints one can perform the arithmetic in long precision and cast the result back to an int, e.g.: int saturatedAdd(int x, int y) { long sum = (long) x + (long) y; long clampedSum = Math.max((long) Integer.MIN_VALUE, Math.min(sum, (long) Integer.MAX_VALUE)); return (int) clampedSum; } or import com.google.common.primitives.Ints; int saturatedAdd(int x, int y) { long sum = (long) x + (long) y; return Ints.saturatedCast(sum); } but in the case of long there is no larger primitive type that can hold the intermediate (unclamped) sum. Since this is Java, I cannot use inline assembly (in particular SSE's saturated add instructions.) It can be implemented using BigInteger, e.g. static final BigInteger bigMin = BigInteger.valueOf(Long.MIN_VALUE); static final BigInteger bigMax = BigInteger.valueOf(Long.MAX_VALUE); long saturatedAdd(long x, long y) { BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y)); return bigMin.max(sum).min(bigMax).longValue(); } however performance is important so this method is not ideal (though useful for testing.) I don't know whether avoiding branching can significantly affect performance in Java. I assume it can, but I would like to benchmark methods both with and without branching. Related: http://stackoverflow.com/questions/121240/saturating-addition-in-c

    Read the article

  • Euler Problem 20

    - by MarkPearl
    This was probably one of the easiest ones to complete – a quick bash got me the following… The Problem n! means n (n 1) ... 3 2 1 For example, 10! = 10 9 ... 3 2 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! The Solution   private static BigInteger Factorial(int num) { if (num > 1) return (BigInteger)num * Factorial(num - 1); else return 1; } private static BigInteger SumDigits(string digits) { BigInteger result = 0; foreach (char number in digits) { result += Convert.ToInt32(number)-48; } return result; } static void Main(string[] args) { Console.WriteLine(SumDigits(Factorial(100).ToString())); Console.ReadLine(); }

    Read the article

< Previous Page | 1 2 3 4  | Next Page >