Example #1
1
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    long n = scanner.nextLong();
    long m = scanner.nextLong();
    Map<Integer, Integer> nmap = primeDivisorAndCounts(n);
    Map<Integer, Integer> mmap = primeDivisorAndCounts(m);

    int sameCount = 1;

    for (Map.Entry<Integer, Integer> entry : nmap.entrySet()) {
      int divisor = entry.getKey();
      int counts = 0;
      if (mmap.containsKey(divisor)) {
        int nc = entry.getValue();
        int mc = mmap.get(divisor);
        counts = nc < mc ? nc : mc;
      }
      sameCount *= counts + 1;
    }

    int nDiviorsCount = 1;
    for (Map.Entry<Integer, Integer> entry : nmap.entrySet()) {
      nDiviorsCount *= entry.getValue() + 1;
    }
    int mDiviorsCount = 1;
    for (Map.Entry<Integer, Integer> entry : mmap.entrySet()) {
      mDiviorsCount *= entry.getValue() + 1;
    }

    int maxCount = nDiviorsCount * mDiviorsCount;

    int maxDivisor = gcd(maxCount, sameCount);

    System.out.println(maxCount / maxDivisor + " " + sameCount / maxDivisor);
  }
  public void solve() {
    try (Scanner scanner = new Scanner(file)) {
      int T = scanner.nextInt();
      for (int t = 1; t <= T; ++t) {
        int n = scanner.nextInt();

        Vector v1 = new Vector(n);
        for (int i = 0; i < n; ++i) {
          v1.setCoord(i, scanner.nextLong());
        }
        Vector v2 = new Vector(n);
        for (int i = 0; i < n; ++i) {
          v2.setCoord(i, scanner.nextLong());
        }
        long min = 0;
        v1.sort();
        v2.sortReverse();
        for (int i = 0; i < n; ++i) {
          min += v1.getCoord(i) * v2.getCoord(i);
        }
        System.out.println("Case #" + t + ": " + min);
      }
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    }
  }
Example #3
0
 /** @param args the command line arguments */
 public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   int T = sc.nextInt();
   for (int i = 0; i < T; i++) {
     int N = sc.nextInt();
     long M = sc.nextLong();
     long high = 0;
     long values[] = new long[N];
     for (int j = 0; j < N; j++) {
       values[j] = sc.nextLong();
     }
     for (int k = 0; k < N; k++) {
       for (int l = 0; l < N; l++) {
         long temp[] = Arrays.copyOfRange(values, l, l + k + 1);
         // System.out.println(Arrays.toString(temp));
         long sum = 0;
         for (int m = 0; m < temp.length; m++) {
           sum += temp[m];
         }
         long mod = sum % M;
         if (mod > high) {
           high = mod;
         }
       }
     }
     System.out.println(high);
   }
 }
  /**
   * Read in the cached DU value and return it if it is less than 600 seconds old (DU update
   * interval). Slight imprecision of dfsUsed is not critical and skipping DU can significantly
   * shorten the startup time. If the cached value is not available or too old, -1 is returned.
   */
  long loadDfsUsed() {
    long cachedDfsUsed;
    long mtime;
    Scanner sc;

    try {
      sc = new Scanner(new File(currentDir, DU_CACHE_FILE), "UTF-8");
    } catch (FileNotFoundException fnfe) {
      return -1;
    }

    try {
      // Get the recorded dfsUsed from the file.
      if (sc.hasNextLong()) {
        cachedDfsUsed = sc.nextLong();
      } else {
        return -1;
      }
      // Get the recorded mtime from the file.
      if (sc.hasNextLong()) {
        mtime = sc.nextLong();
      } else {
        return -1;
      }

      // Return the cached value if mtime is okay.
      if (mtime > 0 && (Time.now() - mtime < 600000L)) {
        FsDatasetImpl.LOG.info("Cached dfsUsed found for " + currentDir + ": " + cachedDfsUsed);
        return cachedDfsUsed;
      }
      return -1;
    } finally {
      sc.close();
    }
  }
Example #5
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    TreeMap<Long, Long> tmap = new TreeMap<>();
    long res = 0;
    while (t-- > 0) {
      res = 0;
      int n = in.nextInt();
      long m = in.nextLong();
      tmap.clear();
      long[] arr = new long[n];
      res = in.nextLong();
      arr[0] = res % m;
      res = Long.MIN_VALUE;
      tmap.put(arr[0], arr[0]);
      for (int i = 1; i < arr.length; i++) {
        arr[i] = in.nextLong();
        arr[i] %= m;
        arr[i] += arr[i - 1];
        arr[i] %= m;

        if (tmap.higherEntry(arr[i]) == null) {
          res = Math.max(res, arr[i]);
          tmap.put(arr[i], arr[i]);
          continue;
        }
        long val = tmap.higherEntry(arr[i]).getValue();
        res = Math.max(res, (arr[i] - val + m) % m);
        tmap.put(arr[i], arr[i]);
      }

      System.out.println(res);
    }
  }
  private static void sortIsbn(Book[] roughBkArr) {
    Scanner keyboard = new Scanner(System.in);
    boolean uniqueIsbn;
    long isSameIsbn = 0;

    for (int i = 0; i < roughBkArr.length; i++) { // Cycle through array in order to find duplicates
      for (int j = i + 1; j < roughBkArr.length; j++) {
        if (roughBkArr[i].getIsbn()
            == roughBkArr[j]
                .getIsbn()) { // Compare ISBNs, if duplicate found prompt user to enter a new ISBN
          System.out.println(
              "Duplicate ISBN " + roughBkArr[j].getIsbn() + " detected in record #" + j + ".");
          System.out.println("Please enter the correct ISBN: ");
          boolean done = false;
          while (!done) {
            try {

              isSameIsbn =
                  keyboard
                      .nextLong(); // Store new ISBN in temporary variable so that we can test it
                                   // isn't another duplicate
              done = true;
            } catch (Exception e) {
              System.out.println("Invalid input! Please enter a valid ISBN");
              keyboard.next();
            }
          }

          uniqueIsbn = false;

          while (!uniqueIsbn) { // Commence a while loop in order to know when an ISBN is not a
                                // duplicate
            try {
              for (int k = 0;
                  k < roughBkArr.length;
                  k++) // Compare if newly entered ISBN is a duplicate or not by cycling through
                       // array
              if (isSameIsbn == roughBkArr[k].getIsbn()) throw new DuplicateIsbnException();

              uniqueIsbn = true; // If no duplicate found can end while loop
            } catch (
                DuplicateIsbnException
                    e) { // DuplicateIsbnException caught, displays which exception found and
                         // prompts for a new ISBN
              System.out.println(e.getMessage());
              System.out.println("Please enter another ISBN: ");
              isSameIsbn =
                  keyboard
                      .nextLong(); // Takes new ISBN and will restart while loop and ensure it isn't
                                   // again a duplicate
            }
          }
          roughBkArr[j].setIsbn(
              isSameIsbn); // Stores newly entered ISBN, whether it be the originally entered new
                           // ISBN or ISBN that
        } // threw the exception
      }
    }
    keyboard.close(); // closing keyboard Scanner for the sortBooks method
  }
Example #7
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner in = new Scanner(System.in);
    Hashtable numbers = new Hashtable();

    N = in.nextInt();
    K = in.nextLong();

    long[] arr = new long[N];
    for (int i = 0; i < N; i++) {
      arr[i] = in.nextLong();
      numbers.put(Long.toString(arr[i]), arr[i]);
    }

    result = 0;

    for (int i = 0; i < N; i++) {
      long tmp = 0, tmp2 = 0;
      tmp = arr[i] + K;
      try {
        tmp2 = (Long) numbers.get(Long.toString(tmp));
        result++;
      } catch (Exception ex) {

      }
    }

    System.out.println(result);
  }
Example #8
0
  @Test
  @Category(UnitTest.class)
  public void writeSplitsPath() throws IOException {
    Splits splits = new PartitionerSplit();
    splits.generateSplits(new TestGenerator());

    File splitfile = folder.newFolder(testName.getMethodName());

    splits.writeSplits(new Path(splitfile.toURI()));

    FileInputStream in = new FileInputStream(new File(splitfile, "partitions"));
    Scanner reader = new Scanner(in);

    Assert.assertEquals("Wrong number written", generated.length, reader.nextInt());

    PartitionerSplit.PartitionerSplitInfo[] si =
        (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits();

    for (int i = 0; i < generated.length; i++) {
      Assert.assertEquals("Splits entry not correct", generated[i].longValue(), reader.nextLong());
      Assert.assertEquals("Partition entry not correct", i, reader.nextLong());
    }

    reader.close();
  }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
Example #10
0
 public static void main(String args[]) {
   Scanner scan = new Scanner(System.in);
   long T = scan.nextLong();
   for (long i = 0; i < T; i++) {
     long N = scan.nextLong() - 1;
     long sum = ap(N / 3, 3, 3) + ap(N / 5, 5, 5) - ap(N / 15, 15, 15);
     System.out.println(sum);
   }
 }
 public static void main(String[] args) {
   /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
   Scanner scan = new Scanner(System.in);
   long T = scan.nextLong();
   for (long i = 0; i < T; i++) {
     long N = scan.nextLong();
     long diff = 0;
     diff = wholeSum(N) - indiSum(N);
     System.out.println(diff);
   }
 }
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   long m, n, r;
   System.out.println("m=");
   m = scanner.nextLong();
   System.out.println("n=");
   n = scanner.nextLong();
   Injector injector = Guice.createInjector(new AppModule());
   ICmmdc obj = injector.getInstance(ICmmdc.class);
   r = obj.cmmdc(m, n);
   System.out.println("Cmmdc : " + r);
 }
 public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
   int t = in.nextInt();
   for (int i = 0; i < t; i++) {
     Set<Long> answer = ManasaandStones(in.nextLong(), in.nextLong(), in.nextLong());
     Iterator<Long> iterator = answer.iterator();
     while (iterator.hasNext()) {
       System.out.printf("%d ", iterator.next());
     }
     System.out.println();
   }
   in.close();
 }
 /**
  * . This is a XOR
  *
  * @author Xiaoming
  * @date 2016年1月13日 下午10:07:27
  */
 public void variableExchage() {
   Scanner scan = new Scanner(System.in); // Create Scanner
   System.out.println("Please input a Integer");
   long number1 = scan.nextLong();
   System.out.println("Please input other Integer");
   long number2 = scan.nextLong();
   System.out.println("Number1 = " + number1 + "; Number2 =  " + number2);
   System.out.println("VariableExchage(XOR) starting :");
   number1 = number1 ^ number2;
   number2 = number2 ^ number1;
   number1 = number1 ^ number2;
   System.out.println("Number1 = " + number1 + "; Number2 =  " + number2);
 }
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    long costOfFirst = input.nextLong();
    long numDollars = input.nextLong();
    long numWants = input.nextLong();

    long counter = 0;
    for (int i = 1; i <= numWants; i++) {
      counter += i * costOfFirst;
    }

    System.out.println(counter - numDollars > 0 ? counter - numDollars : 0);
  }
Example #16
0
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Scanner in = new Scanner(System.in);
   long stones = in.nextLong();
   long total = 0;
   long weight;
   long strenght = in.nextLong();
   for (int i = 0; i < stones; i++) {
     if ((weight = in.nextLong()) <= strenght) {
       total += weight;
     }
   }
   System.out.println(total);
 }
  private static boolean getNumberOfLines(File file, int total, float mean) {

    try {
      double difSum = 0;
      long last, actual;
      int nLines = 0;

      Scanner scan = new Scanner(file);
      scan.useLocale(Locale.US);

      if (scan.hasNextLine()) {
        scan.nextLine();
        if (scan.hasNextLong() && scan.hasNextLine()) {
          last = scan.nextLong();
          nLines++;
          scan.nextLine();
        } else {
          scan.close();
          return false;
        }
      } else {
        scan.close();
        return false;
      }

      while (scan.hasNextLong()) {
        actual = scan.nextLong();
        nLines++;
        difSum += actual - last;
        last = actual;

        if (scan.hasNextLine()) {
          scan.nextLine();
        } else {
          break;
        }
      }

      scan.close();

      total = nLines;
      mean = (float) difSum / (total - 1);

      return true;
    } catch (FileNotFoundException e1) {
      return false;
    }
  }
Example #18
0
  public static void registerPatients(Socket socket) {
    Scanner scanner = new Scanner(System.in);
    long ICint = 0;
    String IC = null;
    int count = 0;

    try {
      System.out.println("Enter IC : ");
      ICint = scanner.nextLong();
    } catch (InputMismatchException e) {
      System.out.println("Please enter only integers.");
      return;
    }

    IC = String.valueOf(ICint);
    System.out.println("Searching for patient..");

    for (int i = 0; i < patientList.size(); i++) {
      if (patientList.get(i).IC.equals(IC)) {
        count++;
        System.out.println("Patient found! Added to queue.\n\n");
        patientQueue.add(patientList.get(i));
      }
    }

    if (count == 0) {
      System.out.println("Patient not found. Registering new entry.\n");
      registerNewPatient(IC, socket);
    }
  }
Example #19
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner scan = new Scanner(System.in);
    System.out.println("input A");
    long A = scan.nextLong();
    System.out.println("input B");
    long B = scan.nextLong();
    System.out.println("A=" + A + "\t+B=" + B);
    System.out.println("swap A , B");
    A = A ^ B;
    B = B ^ A;
    A = A ^ B;
    System.out.println("A=" + A + "\t+B=" + B);
    scan.close();
  }
Example #20
0
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);

    long barcode = input.nextLong();

    long digitvalue =
        (long) ((barcode / 10)); // gets rid of the last digit since that will be our check
    long sum = (digitvalue % 10) * (2);

    // System.out.println(digitvalue); testing code

    for (int i = 2; i < 10; i++) {
      digitvalue = ((digitvalue / 10)); // take 1234567891. We will be moving from right to left.
      // so that the first digit should be 9, 8, 7, 6, 5.....
      // the digitvalue will add to sum everytime it goes through the loop.
      // System.out.println(digitvalue);test code
      sum += (digitvalue % 10) * (i + 1); // this is the section that will add to the sum.

      // System.out.println(sum);
    }
    long checksum = sum % 11;
    long lastdigit = ((long) (barcode % 10));
    if (checksum == lastdigit) {
      System.out.println("This is a valid ISBN code!");
    } else {
      System.out.println("The correct ISBN should be " + checksum);
    }

    // System.out.println(sum); //testing code
    // System.out.println(checksum);
    // System.out.println(lastdigit);

  } // end main method
  public static void main(String[] args) {
    // Kreiramo skener za unos.
    Scanner input = new Scanner(System.in);

    // korisnikov unos
    long index = 0;

    // varijabla za proveru unosa
    boolean check = true;

    // provera unosa
    while (check) {
      try {
        System.out.println("Enter an index for a Fibonacci number: ");
        index = input.nextLong();
        if (index >= 0) {
          // pozivamo metodu i stampamo rezultat
          System.out.println("The Fibonacci number at index " + index + " is " + fib(index));
          check = false;
        }
        // u slucaju greske unosa
      } catch (InputMismatchException e) {
        input.nextLine();
      }
    }
    // zatvaramo unos
    input.close();
  }
Example #22
0
  public static void main(String[] args) {
    scn = new Scanner(System.in);
    int T = scn.nextInt();

    for (int i = 0; i < T; i++) {
      N = scn.nextInt();
      matrix = new long[101][101][101];
      int M = scn.nextInt();
      long[][][] actual = new long[101][101][101];

      for (int j = 0; j < M; j++) {
        String type = scn.next();

        if (type.equals("UPDATE")) {
          int x = scn.nextInt(), y = scn.nextInt(), z = scn.nextInt();
          long W = scn.nextLong();
          update(x, y, z, W - actual[x][y][z]);
          actual[x][y][z] = W;
        } else {
          int x1 = scn.nextInt(), y1 = scn.nextInt(), z1 = scn.nextInt();
          int x2 = scn.nextInt(), y2 = scn.nextInt(), z2 = scn.nextInt();
          long v1 =
              sum(x2, y2, z2) - sum(x1 - 1, y2, z2) - sum(x2, y1 - 1, z2) + sum(x1 - 1, y1 - 1, z2);
          long v2 =
              sum(x2, y2, z1 - 1)
                  - sum(x1 - 1, y2, z1 - 1)
                  - sum(x2, y1 - 1, z1 - 1)
                  + sum(x1 - 1, y1 - 1, z1 - 1);
          System.out.println(v1 - v2);
        }
      }
    }
  }
  // returns a set of perfect numbers
  public static void main(String[] args) {
    // define variables and object
    long limit;
    double exponent;
    Scanner input = new Scanner(System.in);

    /*enter a number (less than 19 digits long)
     * but greater than the largest desired perfect number*/
    System.out.println("Enter upper limit for perfect " + "numbers (up to eighteen digits): ");
    limit = input.nextLong();

    // calculation of Euclid-Euler theorem Mersenne primes
    exponent = (Math.log(.5 + Math.sqrt(2 * limit + .25)) / Math.log(2));
    /*cycle through the set of factors to find the set of primes
    associated with the user's chosen limit*/
    for (int prime = 2; prime <= exponent; prime++) {

      /*call isMersenne to check if the counter
      is a Mersenne prime*/
      if (isMersenne(prime)) {

        // calculates and prints the associated perfect number
        isPerfect(prime);
      } // end if
    } // end for
    input.close();
  } // end main
Example #24
0
  /** @param args */
  public static void main(String[] args) {
    try {
      CardValidator cv = (CardValidator) Naming.lookup("rmi://172.25.12.148/Cards");

      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the cardNo");
      long cardNo = scanner.nextLong();
      System.out.println("Enter the amount");
      float amount = scanner.nextFloat();

      boolean flag = cv.validateCard(cardNo, amount);
      if (flag) {
        System.out.println("Card Accepted");
      } else {
        System.out.println("Card Declined");
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NotBoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #25
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    long a = in.nextLong();
    long b = in.nextLong();

    System.out.println(gcd(a, b));
  }
  public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);

    int sizeOfArray = scn.nextInt();
    long[] array = new long[sizeOfArray];

    for (int i = 0; i < array.length; i++) {
      array[i] = scn.nextLong();
    }

    String command = scn.next();

    while (!command.equals("stop")) {
      String line = scn.nextLine().trim();
      int[] params = new int[2];

      if (command.equals("add") || command.equals("subtract") || command.equals("multiply")) {
        String[] stringParams = line.split(" ");
        params[0] = Integer.parseInt(stringParams[0]);
        params[1] = Integer.parseInt(stringParams[1]);

        performAction(array, command, params);
      } else if (command.equals("rshift")) {
        arrayShiftRight(array);
      } else if (command.equals("lshift")) {
        arrayShiftLeft(array);
      }

      printArray(array);
      System.out.print('\n');

      command = scn.next();
    }
  }
  /** @param args */
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // read the inputs
    long input = scanner.nextLong();

    scanner.close();

    if (input >= 0) {
      System.out.println(input);
      return;
    }

    input = -input;
    long temp = input % 100;
    input /= 100;

    long last = temp % 10;
    long before = temp / 10;

    input = input * 10 + Math.min(last, before);
    input = -input;

    System.out.println(input);
  }
Example #28
0
  public static void main(String[] args) throws IOException {
    Scanner scr = new Scanner(System.in);

    System.out.print("Enter the number of jobs: ");
    int n = scr.nextInt();

    Set<Job> jobs = new HashSet<>();
    System.out.println("Enter the arrival time and burst time of each job");
    for (int i = 1; i <= n; i++) jobs.add(new Job(i, scr.nextLong(), scr.nextLong(), 1));

    JobSchedule sjf = new SJF(jobs);
    System.out.println("Average Turn Around Time: " + sjf.averageTurnAroundTime());
    System.out.println("Average Waiting Time: " + sjf.averageWaitingTime());

    scr.close();
  }
Example #29
0
  public static void main(String args[]) {

    // create a scanner
    Scanner userInput = new Scanner(System.in);

    // the three variables
    long value1, value2, value3;

    try {
      System.out.print("Enter integer one: ");
      value1 = userInput.nextLong();

      System.out.print("Enter integer two: ");
      value2 = userInput.nextLong();

      System.out.print("Enter integer three: ");
      value3 = userInput.nextLong();

      System.out.println(
          "The integers in the entered order are: " + value1 + ", " + value2 + ", " + value3);

      // in the temp variable store one of the values when swapping
      long temp;
      if (value2 < value1) {
        temp = value1;
        value1 = value2;
        value2 = temp;
      }
      if (value3 < value2) {
        temp = value3;
        value3 = value2;
        value2 = temp;
      }
      if (value2 < value1) {
        temp = value1;
        value1 = value2;
        value2 = temp;
      }

      System.out.println("The sorted integers are: " + value1 + ", " + value2 + ", " + value3);

    } catch (InputMismatchException e) {

      // Error message is displayed if the user entered an invalid integer
      System.out.println("You must enter an integer!");
    }
  }
    @Override
    public RangeWritable getCurrentKey() throws IOException, InterruptedException {

      String sKey = reader.getCurrentKey().toString();
      Scanner scanner = new Scanner(sKey);
      return new RangeWritable(scanner.nextLong(), scanner.nextLong());
    }