File: floorPow2.cpp

package info (click to toggle)
primesieve 12.12%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,952 kB
  • sloc: cpp: 16,515; ansic: 723; sh: 531; makefile: 91
file content (75 lines) | stat: -rw-r--r-- 1,589 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
///
/// @file   floorPow2.cpp
/// @brief  Round down to nearest power of 2.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/pmath.hpp>

#include <stdint.h>
#include <iostream>
#include <cmath>
#include <cstdlib>

void check(bool OK)
{
  std::cout << "   " << (OK ? "OK" : "ERROR") << "\n";
  if (!OK)
    std::exit(1);
}

uint64_t floorPow2_cmath(uint64_t n)
{
  return 1ull << (uint64_t) std::log2(n);
}

int main()
{
  uint64_t n;
  uint64_t res1;
  uint64_t res2;

  for (n = 1; n < 100000; n++)
  {
    res1 = floorPow2(n);
    res2 = floorPow2_cmath(n);
    std::cout << "floorPow2(" << n << ") = " << res1;
    check(res1 == res2);
  }

  n = (1ull << 32) - 1;
  res1 = floorPow2(n);
  res2 = floorPow2_cmath(n);
  std::cout << "floorPow2(" << n << ") = " << res1;
  check(res1 == res2);

  n = 1ull << 32;
  res1 = floorPow2(n);
  res2 = floorPow2_cmath(n);
  std::cout << "floorPow2(" << n << ") = " << res1;
  check(res1 == res2);

  n = (1ull << 63) - 1;
  res1 = floorPow2(n);
  std::cout << "floorPow2(" << n << ") = " << res1;
  check(res1 == (1ull << 62));

  n = 1ull << 63;
  res1 = floorPow2(n);
  std::cout << "floorPow2(" << n << ") = " << res1;
  check(res1 == (1ull << 63));

  n = 18446744073709551615ull;
  res1 = floorPow2(n);
  std::cout << "floorPow2(" << n << ") = " << res1;
  check(res1 == (1ull << 63));

  std::cout << std::endl;
  std::cout << "All tests passed successfully!" << std::endl;

  return 0;
}