繁体   English   中英

最有效的方法来添加数字的单个数字

[英]Most efficient way to add individual digits of a number

我正在研究一种算法,以确定给定的数字是否为质数并且是否访问了此网站 但是后来我尝试了自己的逻辑。 我可以轻松地消除以2,4,5,6,8结尾的数字(对于大于5的数字,则为0),所以我剩下1,3,7和9作为可能的最后一位数字。 现在,如果最后一位是3,我可以将各个数字加起来以检查是否可以被3整除。我不想执行模数(%)运算并将其相加。 有没有一种更有效的方法将十进制数字相加? 也许使用按位运算...?

%或模运算符将比加单个数字快。 但是,如果您确实要执行此操作,则可以部分展开循环,以使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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM