日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

4kyu Sum by Factors

發布時間:2025/3/21 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 4kyu Sum by Factors 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

4kyu Sum by Factors

題目背景:

Given an array of positive or negative integers
I= [i1,…,in]
you have to produce a sorted array P of the form
[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] …]
P will be sorted by increasing order of the prime numbers.

題目分析:

本道題簡單地說就是如何求出某范圍內所有的質數,所以核心的思路就是質數打表如何處理,在OJ題目中,質數打表是很常用的技巧,一般有經典的模板,此處附上我經常用的一個模板,可能和網上流傳的版本有些不同,不過時間復雜度上也是O(n)線性級別的:

std::vector<bool> prime(max + 1, true); for ( int i = 3; i <= max; i++ ) {if ( i % 2 == 0 ) prime[i] = false; } for ( int i = 3; i * i <= max; i++ ) {if ( prime[i] ) {for ( int j = i * i; j <= max; j += 2 * i ) {prime[j] = false;}} } // 最后的prime數組中,prime[i] 為true代表i為質數

最終AC的代碼:

#include <string> #include <vector>class SumOfDivided { public:static std::string sumOfDivided(std::vector<int> &lst); };std::string SumOfDivided::sumOfDivided(std::vector<int> &lst) {int max = 0;for ( int i = 0; i < lst.size(); i++ ) {if ( max < std::abs(lst[i]) ) max = std::abs(lst[i]);}if ( max <= 2 ) return "";std::vector<bool> prime(max + 1, true);for ( int i = 3; i <= max; i++ ) {if ( i % 2 == 0 ) prime[i] = false;}for ( int i = 3; i * i <= max; i++ ) {if ( prime[i] ) {for ( int j = i * i; j <= max; j += 2 * i ) {prime[j] = false;}}}std::string res = "";for ( int i = 2; i <= max; i++ ) {if ( prime[i] ) {long sum = 0;bool flag = false;for ( int j = 0; j < lst.size(); j++ ) {if ( lst[j] % i == 0 ){sum += lst[j];flag = true;}}if ( flag ) res += ('(' + std::to_string(i) + ' ' + std::to_string(sum) + ')');}}return res; }

總結

以上是生活随笔為你收集整理的4kyu Sum by Factors的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。