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

前端 未结 9 654
傲寒
傲寒 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:30

    I'd start by subtracting some big number which is divisible by 7.

    Examples of numbers which are divisible by 7 include 700, 7000, 70000, 140000000, 42000000000, etc.

    In the particular example you gave, try subtracting 280000000000(some number of zeros)0000.

    Even easier to implement, repeatedly subtract the largest possible number like 70000000000(some number of zeros)0000.

    0 讨论(0)
  • 2020-12-17 02:33

    You can compute the value of the number modulo 7.

    That is, for each digit d and value n so far compute n = (10 * n + d) % 7.

    This has the advantage of working independently of the divisor 7 or the base 10.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 02:36

    Most of the divisibility by seven rules work on a digit level, so you should have no problem applying them on your string.

    0 讨论(0)
  • 2020-12-17 02:43

    Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.

    0 讨论(0)
  • 2020-12-17 02:44

    Because I recently did work dealing with breaking up numbers, I will hint that to get specific numbers - which is what you will need with some of the other answers - think about integer division and using the modulus to get digits out of it.

    If you had a smaller number, say 123, how would you get the 1, the 2, and the 3 out of it? Especially since you're working in base 10...

    0 讨论(0)
提交回复
热议问题