您的位置:首页 > 其它

codewars算法习题 6级 C A Rule of Divisibility by 13

2018-03-16 23:01 1431 查看
描述:When you divide the successive powers of 
10
 by 
13
 you get the following remainders of the integer divisions:
1, 10, 9, 12, 3, 4
.Then the whole pattern repeats.Hence the following method: Multiply the right most digit of the number with the left most number in the sequence shown above, the second right most digit to the second left most digit of the number in the sequence. The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary............................................................................Example: What is the remainder when 
1234567
 is divided by 
13
?
7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178
We repeat the process with 178:
8x1 + 7x10 + 1x9 = 87
and again with 87:
7x1 + 8x10 = 87
...........................................................................From now on the sequence is stationary and the remainder of 
1234567
 by 
13
 is the same as the remainder of 
87
 by 
13
9
Call 
thirt
 the function which processes this sequence of operations on an integer 
n (>=0)
thirt
 will return the stationary number.
thirt(1234567)
 calculates 178, then 87, then 87 and returns 
87
.
thirt(321)
 calculates 48, 48 and returns 
48
解析:给定一个数(long long 型),将倒着的个位数与数组1,10,9,12,3,4顺序相乘相加,数组可周而复始,相加的数重复上述过程,直至数不再变化,输出数
算法:两个函数,第一个函数先做上述过程相加的两个数的计算,然后在while循环中如果两数不相等则在传递一个数给另一个数,相等则退出,另一个函数则做上述过程中相加的计算
函数代码:long long thirt(long long n)
{
  long long transmit(long long n);
  long a,b,temp;
  a=transmit(n);
  b=transmit(a);
  if(a==b){return a;}//如果相等则直接返回
  while(a!=b){
      a=transmit(b);//大数换成第三个数
      temp=a;a=b;b=temp;//因为数会越来越小,且上一个返回数变小,所以换位使a>b,并抛弃掉第一个数
  }
  return(a);
}
long long transmit(long long n)//计算相加的函数
{
    int lsl[6]={1,10,9,12,3,4};
    int b=0,a=0,c=0;
    while(n!=0){
      a=(int)n%10;
      n=n/10;
      if(b!=6){
          c+=a*lsl[b];
          b++;
      }
      if(b==6){b=0;}
    }
    return c;
}

更简洁的方法:使用递归,一个函数足矣
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐