2015-04-27 4 views
-1

Я хочу иметь различные операции чисел, чтобы получить число.Отдельные операции/декартово произведение

Например, для числа = 5 результат должен отображаться в System.out.println: 2+3, 6-1, 10-4-3-2-1, 1+6-4+5+2, последний имеет важное значение. Я хочу иметь операнды «+» и «-» с любой комбинацией, которая равна числу, а не только 5, но очень высокие цифры.

Это должно работать для чисел, больших, чем длинных. Я хочу работать с BigInteger.

Как написать код, который производит такие вычисления?

+0

'' 10-4-3-2-1' и 1 + 6 + 4 + 5 + 2' не равны 5. Можете ли вы опубликовать свой ввод, ожидаемый результат и код того, что вы пробовали до сих пор? – jdphenix

ответ

0

Если вы хотите получить полный набор таких операций, это невозможно, поскольку в таком множестве будет бесконечно много элементов в нем.

Однако, если вы хотите конечное число операций, это можно сделать.

  1. Выберите положительное случайное целое число, большее 1. Это будет ваше количество добавлений или вычитаний за одну операцию.
  2. Начать с другого случайного числа. Это будет ваш первый срок.
  3. Если текущее количество терминов + 1 равно общему числу терминов, выберите следующий термин как разность целевого номера и оценку всех условий до настоящего времени.
  4. В противном случае выберите другое случайное число и используйте его как следующий термин.
  5. Повторите с шага 3.

Надеется, что это помогает.

0

Это код, который мы пробовали до сих пор. Число 5 ошибочно рассчитано в примере, потому что мы работаем только с тормозами 1 час со вчерашнего дня 16:30 по этому вопросу, и это должно быть сделано в 12:00 ... = (

У нас серьезно нет идеи

Нужно только 150 номеров, значения которых рассчитываются следующим образом: A (1) = 1, A (1) = 1, A (1) = 1, A (1) = 1, A (1) = 1, A (1) = 1, A (1) п) = 3 * (An-1) -1

пакетов данных;.

import java.math.BigInteger; 
import java.util.HashMap; 
import java.util.Hashtable; 
import java.util.List; 
import java.util.Scanner; 
import java.util.Vector; 

    public class Example { 

     private static int counter; // a counter for the recursive calls in isValueOfA 

     //saves the number the user has entered 
     private static String input;  

     //value to be calculated 
     private static BigInteger userInput = new BigInteger("366"); 
     //some constant values needed for this program 
     private static BigInteger bigIntThree; 
     private static BigInteger bigIntOne; 
     private static BigInteger bigIntZero; 
     //We dont want more than 150 A(N) values so we use an array 
     private static BigInteger arraySize; 
     //array to save the values of a1-a150 
     private static BigInteger[] vectorValues; 
     //HashMap to work with values of A(n) 
     private static Hashtable<Integer, BigInteger> values; 

     /** 
     * @param args 
     */ 
     public static void main(String[] args) { 
      init(); 
      populateHashMap();  
      System.out.println(isValueOfA(userInput)); 

     } 

     /** 
     * Initialize everything needed 
     */ 
     private static void init() { 
      //initialize constant values 
      arraySize = new BigInteger("150"); 
      bigIntZero = new BigInteger("0"); 
      bigIntOne = new BigInteger("1"); 
      bigIntThree = new BigInteger("3"); 

      //we only want 150 A(N) and save the Values of this function in this array 
      vectorValues = new BigInteger[150]; 
      //initialize the hashmap 
      values = new Hashtable<Integer, BigInteger>(); 
      //create the vector 
      createVector(arraySize);  
     } 

     /** 
     * Create the numbers with our formula A(1) = 1, A(N) = 3*A(n-1)-1 
     * @param arraySize maximum 150 
     * @return result recursive call 
     */ 
     private static BigInteger createVector(BigInteger arraySize) { 

      //Case for 0   
      if (arraySize.equals(bigIntZero)) { 
       System.out.println("Stop beeing a fool please..."); 
       return bigIntZero; 
      } 
      //End of recursion 
      if (arraySize.equals(bigIntOne)) { 
       vectorValues[0] = bigIntOne; 
       return bigIntOne; 
      } 

      //start recursion 
      else {    
       Integer position = arraySize.intValue(); 
       BigInteger result = bigIntThree.multiply(createVector(arraySize 
         .subtract(bigIntOne))) 
         .subtract(bigIntOne); 
       vectorValues[position -1] = result; 
       return result; 
      } 
     } 

     /** 
     * Transport Values from the array to our Hashtable 
     * @return just fills the hashtable 
     */ 
     private static void populateHashMap() 
     { 
      for (int i = 0; i < 150; i++) 
      { 
       values.put(i+1, vectorValues[i]); 
       System.out.println("HashMap Added key: "+ (i+1) + " with Value: " + vectorValues[i]);   
      } 
     } 

     /** 
     * Checks if a give parameter is the users input   
     * @param number the number to check 
     * @return true if it is equal 
     */ 
     private static BigInteger isValueOfA(BigInteger number) 
     { 
      System.out.println(counter++); 
       if(values.contains(userInput)) 
       { 
        System.out.println("UserInput was " + userInput + ": Result: + "+ number); 
        return number; 
       } 
       else 
       { 
       return BigInteger.ZERO;     
       } 
     } 
    }//end of class 
Смежные вопросы