예제 #1
0
 private String bigIntToHexString(BigInteger bi) {
   StringBuffer buf = new StringBuffer();
   buf.append("0x");
   String val = bi.toString(16);
   for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
     buf.append('0');
   }
   buf.append(val);
   return buf.toString();
 }
예제 #2
0
파일: 009.java 프로젝트: kyokey/MIPT
 void work() {
   cin = new Scanner(System.in);
   int n = cin.nextInt();
   BigInteger a = BigInteger.ONE;
   BigInteger b = BigInteger.ONE;
   n -= 1;
   for (int i = 0; i < n; i++) {
     BigInteger c = a.add(b);
     a = b;
     b = c;
   }
   System.out.println(b.toString());
 }
예제 #3
0
파일: uva619.java 프로젝트: de-yu/uva
 public static void abcd(String str) {
   BigInteger sum = BigInteger.ZERO;
   StringBuffer n = new StringBuffer("");
   for (int i = 0; i < str.length(); i++) {
     BigInteger ab = BigInteger.valueOf(((int) str.charAt(i)) - 96);
     sum = sum.add(div.pow(str.length() - i - 1).multiply(ab));
   }
   String s = sum.toString();
   for (int i = 0; i < s.length(); i++) {
     if (i % 3 == 0 && i != 0) n.insert(0, ",");
     n.insert(0, s.charAt(s.length() - i - 1));
   }
   while (str.length() < 22) str = str + " ";
   System.out.println(str + "" + n);
 }
예제 #4
0
 public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
   n = in.nextInt();
   l = new BigInteger(in.next());
   k = in.nextInt();
   m = in.nextInt();
   BigInteger w = BigInteger.TEN.pow(m);
   for (int i = 0; i <= n; ++i) a[i] = new BigInteger(in.next());
   for (int i = 0; i < Math.min(k, n + 1); ++i) {
     t = a[0];
     for (int j = 1; j <= n; ++j) {
       t = t.multiply(l);
       t = t.add(a[j]);
     }
     t = t.mod(w);
     q[n][i] = t.mod(w);
     int ret = 0;
     c = t.toString().toCharArray();
     int ll = c.length;
     for (int j = 0; j < Math.min(m, ll); ++j) {
       ret += (c[ll - 1 - j] - '0') * (c[ll - 1 - j] - '0');
     }
     System.out.println(ret);
     l = l.add(BigInteger.ONE);
   }
   if (k > n) {
     for (int i = n - 1; i >= 0; --i) {
       for (int j = 0; j <= i; j++) q[i][j] = q[i + 1][j + 1].subtract(q[i + 1][j]).mod(w);
     }
     for (int i = 1; i <= n; ++i) q[0][i] = q[0][0];
     int po = 1;
     for (int i = n + 1; i < k; ++i) {
       for (int j = 1; j <= n; ++j)
         q[j][(po + j) % (n + 1)] =
             q[j - 1][(po + j - 1) % (n + 1)].add(q[j][(po + j - 1) % (n + 1)]).mod(w);
       int ret = 0;
       c = q[n][(po + n) % (n + 1)].mod(w).toString().toCharArray();
       int ll = c.length;
       for (int j = 0; j < Math.min(m, ll); ++j) {
         ret += (c[ll - 1 - j] - '0') * (c[ll - 1 - j] - '0');
       }
       System.out.println(ret);
       l = l.add(BigInteger.ONE);
       ++po;
     }
   }
 }
  public String getKDigits(int N, int K) {
    BigInteger ret = new BigInteger("1");
    BigInteger ten = new BigInteger("10");

    for (int i = 1; i <= N; i++) {
      ret = ret.multiply(new BigInteger(new Integer(i).toString()));
    }
    System.out.println(ret);

    while (ret.mod(ten).equals(BigInteger.ZERO)) ret = ret.divide(ten);

    String ans = ret.toString();

    if (ans.length() > K) {
      ans = ans.substring(ans.length() - K, ans.length());
    }
    return ans;
  }
예제 #6
0
파일: uva10219.java 프로젝트: de-yu/uva
  public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (scanner.hasNextInt()) {
      int n = scanner.nextInt();
      int k = scanner.nextInt();

      BigInteger sum = BigInteger.ONE;

      for (int i = n; i > n - k; i--) {
        sum = sum.multiply(BigInteger.valueOf(i));
      }
      for (int i = 2; i <= k; i++) {
        sum = sum.divide(BigInteger.valueOf(i));
      }

      System.out.println(sum.toString().length());
    }
  }
예제 #7
0
  public static String md5(File file)
      throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest md = MessageDigest.getInstance("MD5");

    InputStream is = new FileInputStream(file);

    byte[] buffer = new byte[8192];
    int read = 0;

    while ((read = is.read(buffer)) > 0) md.update(buffer, 0, read);

    byte[] md5 = md.digest();
    BigInteger bi = new BigInteger(1, md5);

    is.close();
    String hex = bi.toString(16);
    while (hex.length() < 32) {
      hex = "0" + hex;
    } // Padding
    return hex;
  }
예제 #8
0
파일: fraction.java 프로젝트: Bobgy/module
 public String toString() {
   String res = num.toString();
   if (den.compareTo(BigInteger.ONE) != 0) res += "/" + den.toString();
   return res;
 }
예제 #9
0
  /** @see BigInteger#toString(int) */
  static String bigInteger2String(BigInteger val, int radix) {
    int sign = val.sign;
    int numberLength = val.numberLength;
    int digits[] = val.digits;

    if (sign == 0) {
      return "0"; //$NON-NLS-1$
    }
    if (numberLength == 1) {
      int highDigit = digits[numberLength - 1];
      long v = highDigit & 0xFFFFFFFFL;
      if (sign < 0) {
        v = -v;
      }
      return Long.toString(v, radix);
    }
    if ((radix == 10) || (radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) {
      return val.toString();
    }
    double bitsForRadixDigit;
    bitsForRadixDigit = Math.log(radix) / Math.log(2);
    int resLengthInChars =
        (int) (val.abs().bitLength() / bitsForRadixDigit + ((sign < 0) ? 1 : 0)) + 1;

    char result[] = new char[resLengthInChars];
    int currentChar = resLengthInChars;
    int resDigit;
    if (radix != 16) {
      int temp[] = new int[numberLength];
      System.arraycopy(digits, 0, temp, 0, numberLength);
      int tempLen = numberLength;
      int charsPerInt = digitFitInInt[radix];
      int i;
      // get the maximal power of radix that fits in int
      int bigRadix = bigRadices[radix - 2];
      while (true) {
        // divide the array of digits by bigRadix and convert remainders
        // to characters collecting them in the char array
        resDigit = Division.divideArrayByInt(temp, temp, tempLen, bigRadix);
        int previous = currentChar;
        do {
          result[--currentChar] = Character.forDigit(resDigit % radix, radix);
        } while (((resDigit /= radix) != 0) && (currentChar != 0));
        int delta = charsPerInt - previous + currentChar;
        for (i = 0; i < delta && currentChar > 0; i++) {
          result[--currentChar] = '0';
        }
        for (i = tempLen - 1; (i > 0) && (temp[i] == 0); i--) {;
        }
        tempLen = i + 1;
        if ((tempLen == 1) && (temp[0] == 0)) { // the quotient is 0
          break;
        }
      }
    } else {
      // radix == 16
      for (int i = 0; i < numberLength; i++) {
        for (int j = 0; (j < 8) && (currentChar > 0); j++) {
          resDigit = digits[i] >> (j << 2) & 0xf;
          result[--currentChar] = Character.forDigit(resDigit, 16);
        }
      }
    }
    while (result[currentChar] == '0') {
      currentChar++;
    }
    if (sign == -1) {
      result[--currentChar] = '-';
    }
    return new String(result, currentChar, resLengthInChars - currentChar);
  }
예제 #10
0
 /** Returns a String representation of this MutableBigInteger in radix 10. */
 public String toString() {
   BigInteger b = new BigInteger(this, 1);
   return b.toString();
 }
예제 #11
0
  /** This main method basically tests the different features of the Paillier encryption */
  public static void test() {
    Random rd = new Random();
    long num = 0;
    long num1 = 0;
    BigInteger m = null;
    BigInteger c = null;
    int numberOfTests = 10;
    int j = 0;
    BigInteger decryption = null;
    Paillier esystem = new Paillier();
    PaillierPrivateKey key = KeyGen.PaillierKey(512, 122333356);
    esystem.setDecryptEncrypt(key);
    // let's test our algorithm by encrypting and decrypting a few instances
    for (int i = 0; i < numberOfTests; i++) {
      num = Math.abs(rd.nextLong());
      m = BigInteger.valueOf(num);
      System.out.println("number chosen  : " + m.toString());
      c = esystem.encrypt(m);
      System.out.println("encrypted value: " + c.toString());
      decryption = esystem.decrypt(c);
      System.out.println("decrypted value: " + decryption.toString());
      if (m.compareTo(decryption) == 0) {
        System.out.println("OK");
        j++;
      } else System.out.println("PROBLEM");
    }
    System.out.println(
        "out of "
            + (new Integer(numberOfTests)).toString()
            + "random encryption,# many of "
            + (new Integer(j)).toString()
            + " has passed");
    // Let us check the commutative properties of the paillier encryption
    System.out.println("Checking the additive properteries of the Paillier encryption");
    //   Obviously 1+0=1
    System.out.println(
        "1+0="
            + (esystem.decrypt(esystem.add(esystem.encryptone(), esystem.encryptzero())))
                .toString());
    // 1+1=2
    System.out.println(
        "1+1="
            + (esystem.decrypt(
                    esystem.add(esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE))))
                .toString());

    // 1+1+1=3
    System.out.println(
        "1+1+1="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.add(
                            esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE)),
                        esystem.encrypt(BigInteger.ONE))))
                .toString());

    // 0+0=0
    System.out.println(
        "0+0="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.ZERO), esystem.encrypt(BigInteger.ZERO))))
                .toString());
    // 1+-1=0
    System.out.println(
        "1+-1="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.valueOf(-1).mod(key.getN())),
                        esystem.encrypt(BigInteger.ONE))))
                .toString());

    do {
      num = rd.nextLong();
    } while (key.inModN(BigInteger.valueOf(num)) == false);
    do {
      num1 = rd.nextLong();
    } while (key.inModN(BigInteger.valueOf(num1)) == false);
    BigInteger numplusnum1 = BigInteger.valueOf(num).add(BigInteger.valueOf(num1));
    BigInteger summodnsquare = numplusnum1.mod(key.getN());
    // D(E(num)+E(num1))=num+num1
    System.out.println(numplusnum1.toString());
    System.out.println(
        summodnsquare.toString()
            + "=\n"
            + esystem
                .decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.valueOf(num)),
                        esystem.encrypt(BigInteger.valueOf(num1))))
                .toString());
    // Let us check the multiplicative properties
    System.out.println("Checking the multiplicative properties");
    // D(multiply(E(2),3))=6
    System.out.println(
        "6="
            + esystem.decrypt(
                esystem.multiply(
                    esystem.add(esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE)),
                    3)));
  }
예제 #12
0
 /** Converts a binary string to a hexadecimal string */
 private String bin2hex(String binary) {
   BigInteger hex = new BigInteger(binary, 2);
   return hex.toString(16).toUpperCase();
 }
예제 #13
0
 /** Converts a hexadecimal string to a binary string */
 private String hex2bin(String hex) {
   BigInteger bin = new BigInteger(hex.toLowerCase(), 16);
   return bin.toString(2);
 }
예제 #14
0
 /** Converts a large integer (numeric string) to a binary string */
 private String dec2bin(String decimal) {
   BigInteger bin = new BigInteger(decimal);
   return bin.toString(2);
 }
예제 #15
0
 /** Converts a binary string into a large integer (numeric string) */
 private String bin2dec(String binary) {
   BigInteger dec = new BigInteger(binary, 2);
   return dec.toString();
 }
예제 #16
0
  /** convert from a particular scheme / level */
  private String convertLevel(
      Scheme tdtscheme,
      Level tdtlevel,
      String input,
      Map<String, String> inputParameters,
      LevelTypeList outboundlevel) {

    String outboundstring;
    Map<String, String> extraparams =
        //	    new NoisyMap
        (new HashMap<String, String>(inputParameters));

    // get the scheme's option key, which is the name of a
    // parameter whose value is matched to the option key of the
    // level.

    String optionkey = tdtscheme.getOptionKey();
    String optionValue = extraparams.get(optionkey);
    // the name of a parameter which allows the appropriate option
    // to be selected

    // now consider the various options within the scheme and
    // level for each option element inside the level, check
    // whether the pattern attribute matches as a regular
    // expression

    String matchingOptionKey = null;
    Option matchingOption = null;
    Matcher prefixMatcher = null;
    for (Enumeration e = tdtlevel.enumerateOption(); e.hasMoreElements(); ) {
      Option opt = (Option) e.nextElement();
      if (optionValue == null || optionValue.equals(opt.getOptionKey())) {
        // possible match

        Matcher matcher = Pattern.compile(opt.getPattern()).matcher(input);
        if (matcher.matches()) {
          if (prefixMatcher != null) throw new TDTException("Multiple patterns matched");
          prefixMatcher = matcher;
          matchingOptionKey = opt.getOptionKey();
          matchingOption = opt;
        }
      }
    }
    if (prefixMatcher == null) throw new TDTException("No patterns matched");

    optionValue = matchingOptionKey;

    for (Enumeration e = matchingOption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      int seq = field.getSeq();

      String strfieldname = field.getName();
      int fieldlength = field.getLength();
      String strfieldvalue = prefixMatcher.group(seq);
      // System.out.println("   processing field " + strfieldname + " = '" + strfieldvalue + "'");

      if (field.getCompaction() == null) {
        // if compaction is null, treat field as an integer

        if (field.getCharacterSet() != null) { // if the character set is specified
          Matcher charsetmatcher =
              Pattern.compile("^" + field.getCharacterSet() + "$").matcher(strfieldvalue);
          if (!charsetmatcher.matches()) {
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + strfieldvalue
                    + ") does not conform to the allowed character set ("
                    + field.getCharacterSet()
                    + ") ");
          }
        }

        BigInteger bigvalue = null;

        if (tdtlevel.getType() == LevelTypeList.BINARY) { // if the input was BINARY
          bigvalue = new BigInteger(strfieldvalue, 2);
          extraparams.put(strfieldname, bigvalue.toString());
        } else {
          if (field.getDecimalMinimum() != null || field.getDecimalMaximum() != null)
            bigvalue = new BigInteger(strfieldvalue);
          extraparams.put(strfieldname, strfieldvalue);
        }

        if (field.getDecimalMinimum() != null) { // if the decimal minimum is specified
          BigInteger bigmin = new BigInteger(field.getDecimalMinimum());

          if (bigvalue.compareTo(bigmin)
              == -1) { // throw an exception if the field value is less than the decimal minimum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is less than DecimalMinimum ("
                    + field.getDecimalMinimum()
                    + ") allowed");
          }
        }

        if (field.getDecimalMaximum() != null) { // if the decimal maximum is specified
          BigInteger bigmax = new BigInteger(field.getDecimalMaximum());

          if (bigvalue.compareTo(bigmax)
              == 1) { // throw an excpetion if the field value is greater than the decimal maximum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is greater than DecimalMaximum ("
                    + field.getDecimalMaximum()
                    + ") allowed");
          }
        }

        // after extracting the field, it may be necessary to pad it.

        padField(extraparams, field);

      } else {
        // compaction is specified - interpret binary as a string value using a truncated byte per
        // character

        CompactionMethodList compaction = field.getCompaction();
        PadDirectionList padDir = field.getPadDir();
        String padchar = field.getPadChar();
        String s;
        if (compaction == CompactionMethodList.VALUE_5)
          // "5-bit"
          s = bin2uppercasefive(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_4)
          // 6-bit
          s = bin2alphanumsix(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_3)
          // 7-bit
          s = bin2asciiseven(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_2)
          // 8-bit
          s = bin2bytestring(strfieldvalue);
        else throw new Error("unsupported compaction method " + compaction);
        extraparams.put(strfieldname, stripPadChar(s, padDir, padchar));
      }
    } // for each field;

    /**
     * the EXTRACT rules are performed after parsing the input, in order to determine additional
     * fields that are to be derived from the fields obtained by the pattern match process
     */
    int seq = 0;
    for (Enumeration e = tdtlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.EXTRACT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to consider the corresponding output level and output option. The scheme must
     * remain the same, as must the value of optionkey (to select the corresponding option element
     * nested within the required outbound level)
     */
    Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
    Option tdtoutoption = findOption(tdtoutlevel, optionValue);

    /**
     * the FORMAT rules are performed before formatting the output, in order to determine additional
     * fields that are required for preparation of the outbound format
     */
    seq = 0;
    for (Enumeration e = tdtoutlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.FORMAT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to ensure that all fields required for the outbound grammar are suitably padded
     * etc. processPadding takes care of firstly padding the non-binary fields if padChar and
     * padDir, length are specified then (if necessary) converting to binary and padding the binary
     * representation to the left with zeros if the bit string is has fewer bits than the bitLength
     * attribute specifies. N.B. TDTv1.1 will be more specific about bit-level padding rather than
     * assuming that it is always to the left with the zero bit.
     */

    // System.out.println(" prior to processPadding, " + extraparams);
    for (Enumeration e = tdtoutoption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      // processPadding(extraparams, field, outboundlevel, tdtoutoption);

      padField(extraparams, field);
      if (outboundlevel == LevelTypeList.BINARY) binaryPadding(extraparams, field);
    }

    /**
     * Construct the output from the specified grammar (in ABNF format) together with the field
     * values stored in inputparams
     */
    outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams);

    // System.out.println("final extraparams = " + extraparams);
    // System.out.println("returned " + outboundstring);
    return outboundstring;
  }