[英]Most efficient way to add individual digits of a number
%
或模运算符将比加单个数字快。 但是,如果您确实要执行此操作,则可以部分展开循环,以使3的倍数自动转义。
例如:
2 is prime
3 is prime
candidate = 5
while(candidate <= limit - 2 * 3) // Unrolling loop for next 2 * 3 number
{
if ( CheckPrime(candidate) ) candidate is prime;
candidate += 2;
if ( CheckPrime(candidate) ) candidate is prime;
candidate += 4; // candidate + 2 is multiple of 3 (9, 15, 21 etc)
}
if(candidate < limit) CheckPrime(candidate);
在上面的方法中,我们消除了3的倍数,而不是通过添加数字来检查3的除数。
你观察得很好。 顺便说一句,找到质数称为车轮分解 。 我已经完成了wheel size = 6
(2 * 3)的操作,但是对于较大的车轮尺寸,您也可以这样做,例如:30(2 * 3 * 5)。 上面的代码段也被称为所有素数均为6N±1类型。 (因为6N + 3是3的倍数)
ps并非所有以2和5结尾的数字都是合成的。 2和5是例外。
您可能会考虑以下内容,但我认为模数是最快的方法:
1. 2^n mod 3 = 1 if n is even and = 2 if n is odd
2. odd bits and even bits cancel each out as their sum is zero modulo 3
4. so the absolute difference of odd and even bits is the remainder
5. As difference might be again greater than 3 you need to again calculate modulo 3
6. step 5 can be done recursively
伪代码:-
int modulo3(int num) {
if(num<3)
return num;
int odd_bits = cal_odd(num);
int even_bits = cal_even(num);
return module3(abs(even_bits-odd_bits));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.