Guest User

Untitled

a guest
Oct 20th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. use std::time::Instant;
  2. use std::collections::VecDeque;
  3.  
  4. fn gcd(a: u32, b: u32) -> u32 {
  5. if b != 0 {
  6. gcd(b, a % b)
  7. } else {
  8. a
  9. }
  10. }
  11.  
  12. fn test_naive(n: u32) -> u32 {
  13. let mut ans = 0;
  14. for i in 1..n {
  15. for j in i+1..n {
  16. if gcd(i, j) == 1 && gcd(i, i + j) == 1 && gcd(j, i + j) == 1 {
  17. ans += 1;
  18. }
  19. }
  20. }
  21. ans
  22. }
  23.  
  24. fn f(a: u32, b: u32, n: u32) -> u32 {
  25. let mut ans = 0;
  26. let mut q = VecDeque::new();
  27. q.push_back((a, b));
  28. while let Some((x, y)) = q.pop_front() {
  29. if x < n {
  30. if gcd(x, x + y) == 1 && gcd(y, x + y) == 1 {
  31. ans += 1;
  32. }
  33. q.push_back((2 * x - y, x));
  34. q.push_back((2 * x + y, x));
  35. q.push_back((x + 2 * y, y));
  36. }
  37. }
  38. ans
  39. }
  40.  
  41. fn test_smart(n: u32) -> u32 {
  42. f(2, 1, n) + f(3, 1, n)
  43. }
  44.  
  45. fn main() {
  46. let n = 10000;
  47.  
  48. let now = Instant::now();
  49. let res = test_naive(n);
  50. println!("test_naive({}) = {}; done in {:?}", n, res, now.elapsed());
  51.  
  52. let now = Instant::now();
  53. let res = test_smart(n);
  54. println!("test_smart({}) = {}; done in {:?}", n, res, now.elapsed());
  55. }
Add Comment
Please, Sign In to add comment