How to check for division by 7 for big number in C++?

前端 未结 9 703
傲寒
傲寒 2020-12-17 01:57

I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 02:34

    N = abc

    There is a simple algorithm to verify if a three-digit number is a multiple of 7:

    Substitute a by x and add it to bc, being x the tens of a two-digit number multiple of 7 whose hundreds is a.

    N = 154; x = 2; 2 + 54 = 56; 7|56 and 7|154

    N = 931; x = 4; 4 + 31 = 35; 7|35 and 7|931

    N = 665; x = 5; 5 + 65 = 70; 7|70 and 7|665

    N = 341; x = 6; 6 + 41 = 47; 7ł47 and 7ł341

    If N is formed by various periods the inverse additive of the result of one period must be added to the sum of the next period, this way:

    N = 341.234

    6 + 41 = 47; - 41 mod 7 ≡ 1; 1 + 4 + 34 = 39; 7ł39 and 7łN

    N = 341.234.612.736.481

    The result for 341.234 is 39. Continuing from this result we have:

    -39 mod 7 ≡ 3; 3 + 5 + 6 + 1 + 2 + 1 = 18; - 18 mod 7 ≡ 3; 3 + 0 + 36 = 39; - 39 mod 7 ≡ 3; 3 + 1 + 81 = 85; 7ł85 and 7łN

    This rule may be applied entirely through mental calculation and is very quick. It was derived from another rule that I created in 2.005. It works for numbers of any magnitude and for divisibility by 13.

提交回复
热议问题