integer division vs regular division

坚强是说给别人听的谎言 提交于 2019-12-12 02:18:26

问题


I need to compare an integer in a loop to the quotient of a long and a long. in order to not do integer division, if I understand correctly do I need to convert one of the longs into a double?

long prime = primes[d];
int i = 1;

//  "inputNumber / prime" should not be integer division, while it is now.
//  How do I do this yet still compare it to an "int" afterwards? 
while (i < (inputNumber / prime))
{
    primes[i*prime] = 0;
    i++;
}

That's the code snippet. primes is an array filled with longs. Btw is this code correct:

primes[i*prime] = 0;

because I am worried that a long * int won't work for an array index.

Thanks so much!


回答1:


You can multiply one of the operands of the integer division by 1.0 to avoid integer truncation of the result.




回答2:


Why not while((i * prime) < inputNumber) instead? A long multiplied by an int results in a long...



来源:https://stackoverflow.com/questions/11277986/integer-division-vs-regular-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!