[Uva12716] GCD and XOR

Source: Internet
Author: User
Question

Input integer N (1 <= n <= 3*107). How many pairs of Integers (a, B) meet the following conditions: 1 <= B <= A <= n, and gcd (a, B) = a xor B. For example, when n = 7, there are 4 pairs: (3, 2), (5, 4), (6, 4), (7, 6)

Analysis

The main idea of this question is to find a bridge between gcd (A, B) and a ^ B.

  1. A ^ B ≥ a-B. Oral proof: If the binary bit is the same, the values are all 0. If the binary bit is added, the former must be 1, and the latter may be 1 (1-0 ), it is also possible that the number of digits may be reduced (0-1)
  2. A-B ≥ gcd (A, B ). Gcd (a, B) = gcd (a, a-B) = gcd (B, A-B) can be obtained from the 9-Chapter numerics ). Obviously, a-B is ≥gcd (a, a-B ).

We now know that gcd (a, B) = a ^ B. According to the clamping force method, a ^ B = a-B = gcd (a, B) = gcd (A, B, a-B)

In other words, a ^ B is equal to a-B, and A-B is a factor of.

Therefore, we enumerate a-B, obtain all its multiples, and then judge whether a-B = a ^ B is true. Time complexity O (N + n/2 + N/3 + ...... + N/n) = O (n logn)

Make sure to enclose the brackets. Otherwise, wait for a few WAF releases.

Code
  1. # Include <bits/stdc ++. h>
  2. Using namespace STD;
  3. # Define n 30000003
  4. Int t, n;
  5. Int ans [N];
  6. Int main ()
  7. {
  8. For (INT I = 1; I <n; I ++)
  9. {
  10. For (Int J = I * 2; j <n; j + = I)
  11. If (J ^ (J-I) = I)
  12. Ans [J] ++;
  13. Ans [I] + = ans [I-1];
  14. }
  15. Scanf ("% d", & T );
  16. For (INT I = 1; I <= T; I ++)
  17. {
  18. Scanf ("% d", & N );
  19. Printf ("case % d: % d \ n", I, ANS [N]);
  20. }
  21. }

[Uva12716] GCD and XOR

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.