Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Sum of Multiples

Add values below a limit divisible by any supplied factor.

Bạn sẽ học được gì

  • Test a number against several factors
  • Avoid counting a value twice
  • Accumulate a total below a limit

Đề bài

Xem bản dịch

Consider positive integers strictly below limit. Include a value if it is divisible by at least one nonzero factor. Count each included value once even if several factors divide it. Ignore zero factors. Factors [3, 5] give the familiar multiples-of-3-or-5 task.

Implement sum_of_multiples(limit, factors).

Input

limit: The exclusive upper bound.

factors: The factors whose multiples are eligible.

Output

Return the sum of distinct eligible positive integers.

Ràng buộc

0 ≤ limit ≤ 100,000. There may be 0 through 20 factors, each between 0 and 100,000. Duplicate factors are allowed.

Ví dụ

Ví dụ 1
Đầu vào:
limit = 12
factors = [3, 5]

Kết quả mong đợi:
expected = 33
Đầu vào:
long long limit = 12;
std::vector<long long> factors = {3, 5};

Kết quả mong đợi:
long long expected = 33;
Đầu vào:
long limit = 12;
long[] factors = new long[] {3, 5};

Kết quả mong đợi:
long expected = 33;

Giải thích

The included values are 3, 5, 6, 9, and 10. Their sum is 33.

Ví dụ 2
Đầu vào:
limit = 10
factors = [2, 4]

Kết quả mong đợi:
expected = 20
Đầu vào:
long long limit = 10;
std::vector<long long> factors = {2, 4};

Kết quả mong đợi:
long long expected = 20;
Đầu vào:
long limit = 10;
long[] factors = new long[] {2, 4};

Kết quả mong đợi:
long expected = 20;

Giải thích

Include 2, 4, 6, and 8. Values 4 and 8 are counted once despite matching both factors.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Only values divisible by at least one usable factor should contribute once.

Gợi ý 2

Use inclusion-exclusion to combine overlapping factor multiples without double counting.

Gợi ý 3

Ignore zero factors and duplicates before doing any arithmetic.

Độ phức tạp mong đợi

O(2^m) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.