为什么增加一个正数会返回一个负数? Java

问题描述

我有一个列出质数的程序。我从一个正整数开始,它返回一个包含数字(不应该这样做)的数组(应该这样做)。问题在于代码中的任何地方都没有减量运算符,只有增量运算符和模数函数。这是完整的代码和输出,供您参考,并对其进行了完整注释,以便于理解:

package calculations;

import java.util.ArrayList;

public class PrimeNumbers {
 public static void main(String[] args) {
    
     //Declaring variables to be used...
     ArrayList<Integer> listOfPrimes = new ArrayList<Integer>();
     listOfPrimes.add(2);
     int numOfPrimesToList = 10;
     int possiblePrimeCounter  = 0;
     
     /* We start testing at the number 2 and increment until 
      * the list of primes we have listed is equal to the
      * number of primes want to list. 
      */
     for(int atNum = 2; listOfPrimes.size() < numOfPrimesToList; atNum++) {
        
         /* While the index of the number to divide from 
          * is less than the length of our list,we do 
          * the following:
          */
         for(int intIndexToCheck = 0; intIndexToCheck < listOfPrimes.size(); intIndexToCheck++) {
            
             /* If the modulus of the number we are testing 
              * and the one are dividing by is greater than
              * zero,we increment its possibility of being
              * a prime by one. 
              */
             if(atNum % listOfPrimes.get(intIndexToCheck) < 0) {
                 possiblePrimeCounter++;
                
                 /* If its chance of being a prime is 1 (that is,the
                  * times it has been given a chance is equal to the
                  * total number of possible chances it is given),then
                  * we can consider it to be a prime.
                  */
                 if(possiblePrimeCounter == listOfPrimes.size()) {
                     //We then add this number to the list of primes.
                     listOfPrimes.add(atNum);
                    
                     possiblePrimeCounter = 0;
                 }
             }
         }
     }
     //Finally,we print out the list of primes.
     System.out.println(listOfPrimes);
 }
}

返回:

[2,-2147483647,-2147483645,-2147483644,-2147483643,-2147483641,-2147483640,-2147483639,-2147483638,-2147483637]

解决方法

发生的事情称为整数溢出。 当int变为最大值(Integer.MAX_VALUE)时,如果尝试递增,它将返回到其最小值(Integer.MIN_VALUE),即您得到的数字。

,

问题是您的代码没有执行您的注释所说明的。你有

var collections=[
    {value:20,next:"",prev: "",lastUpdated: false,isLoaked: false,pointer: false},{value:20,pointer: false}
];
var maxValue = 100;
var totalValue = 0;
var toBeDistributedNext = 0;
var toBeDistributedPrev = 0;

for(i = 0; i < collections.length; i++) {
    collections[i].next = (i+1) % collections.length;
  collections[i].prev = i > 0 ? i-1 : collections.length-1;
}

collections[2].value = 25;
collections[2].pointer = true;

collections.forEach(function (collection) {
  totalValue += parseInt(collection.value);
});

if (totalValue > maxValue) {
    toBeDistributedNext = totalValue - maxValue;
} else {
    toBeDistributedPrev = maxValue - totalValue;
}
console.log('BEFORE',collections);
var currentPointer = collections.find(item => item.pointer === true);
for (let i = 0; i < toBeDistributedNext; i++) {
  var nextIndex = currentPointer.next;
  if (!collections[nextIndex].pointer) {
    collections[nextIndex].value--;
    collections[nextIndex].lastUpdated = true;
  } else {
    toBeDistributedNext++;
  }
  
  currentPointer = collections[nextIndex];
}

console.log("AFTER",collections)

    /*if (collections[i%collections.length].pointer && !collections[i%collections.length].lastUpdated) {
    collections[collections[i%collections.length].next%collections.length].value++;
    collections[collections[i%collections.length].next%collections.length].lastUpdated = true;
  } else {
    //????Need help,So it moves to next item and add one as you see the expected result
  }*/
/**Expected Result: with NEXT
0: {value: 19,next: 1,prev: 4,lastUpdated: true,pointer: false}
1: {value: 19,next: 2,prev: 0,pointer: false}
2: {value: 25,next: 3,prev: 1,pointer: true}
3: {value: 18,next: 4,prev: 2,pointer: false}
4: {value: 19,next: 0,prev: 3,pointer: false}
*/

/**Expected Result: with PREV
0: {value: 20,pointer: false}
1: {value: 20,pointer: false}
2: {value: 23,pointer: false}
*/

//So if its LOCKED,it will (100 - totalLocaked) and what ever is left will be distributed similary with next and prev.

它表示您检查的更大大于零,但实际上它检查的小于零。更改行以实际执行评论所说的

         /* If the modulus of the number we are testing 
          * and the one are dividing by is greater than
          * zero,we increment its possibility of being
          * a prime by one. 
          */
         if(atNum % listOfPrimes.get(intIndexToCheck) < 0) {

由于您要测试小于零的余数(对于正数永远不会发生),因此请不断增加数字直到溢出并变为负数,此时余数的确小于零。

对于您的跟进问题,如果您的电话号码不是素数,则不会重置hypothePrimeCounter,因此possiblePrimeCounter会继续测试下一个电话号码。另外,在添加素数后,您还要进行另一项测试,并检查它是否可以自己整除(因为您只是增加了列表的大小)。

一个简单的解决方法是

         if(atNum % listOfPrimes.get(intIndexToCheck) > 0) {

或者使循环更有效率,只要我们知道数字不是素数,就无需继续测试。

     possiblePrimeCounter = 0; // Need to reset before trying each new number
     for(int intIndexToCheck = 0; intIndexToCheck < listOfPrimes.size(); intIndexToCheck++) {

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...