Bazida velosiped tuzib chiqish (Yane hamma narsani qo'lda yozish) kerak bo'lsa (Customize)
lekin ko'pgina holatlarda bu zararli hisoblanadi. Chunki bu bizni productivligimizga jiddiy tasir kursatadi.
Qo'lda yozish odatda o'rganish yoki biror bir kamchiliklarni to'ldirish maqsadida amalga oshiriladi.
Misol uchun oddiygina masala Massivdan ikkilamchi elementlarni o'chirish muammosini ko'ramiz.
Masala shartini uqib chiqsak unda massiv o'suvchan ekanligini kurishimiz mumkin.
O'suvchan massivda bir xil elementlar ketma ket bulishi aniq.
Shunchaki ularni olib oxiriga joylashtirib keyin yangi massivga utkazsak buldi.
Albatta buni qo'limizda yozib massivni elementlarini siljitib amalga oshirishimiz mumkin.
Yoki dasturlash tilidagi tayor funksionaldan ham foydalanish mumkin. Bazi dasturlash tillari standart boy algoritmlardan tashkil topgan
agar biz ishlatayotgan instrument -dasturlash tilida shu imkoniyat standart mavjud bulsa u holda shunchaki undan foydalanish kifoya.
lekin ko'pgina holatlarda bu zararli hisoblanadi. Chunki bu bizni productivligimizga jiddiy tasir kursatadi.
Qo'lda yozish odatda o'rganish yoki biror bir kamchiliklarni to'ldirish maqsadida amalga oshiriladi.
Misol uchun oddiygina masala Massivdan ikkilamchi elementlarni o'chirish muammosini ko'ramiz.
Masala shartini uqib chiqsak unda massiv o'suvchan ekanligini kurishimiz mumkin.
O'suvchan massivda bir xil elementlar ketma ket bulishi aniq.
Shunchaki ularni olib oxiriga joylashtirib keyin yangi massivga utkazsak buldi.
Albatta buni qo'limizda yozib massivni elementlarini siljitib amalga oshirishimiz mumkin.
Yoki dasturlash tilidagi tayor funksionaldan ham foydalanish mumkin. Bazi dasturlash tillari standart boy algoritmlardan tashkil topgan
agar biz ishlatayotgan instrument -dasturlash tilida shu imkoniyat standart mavjud bulsa u holda shunchaki undan foydalanish kifoya.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
auto last = std::unique(nums.begin(), nums.end());
nums.erase(last, nums.end());
return nums.size();
}
};
LeetCode
Remove Duplicates from Sorted Array - LeetCode
Can you solve this real interview question? Remove Duplicates from Sorted Array - Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique element appears…
👍5⚡4
LeetCode 139. Single Number
Bir qarashda juda oson tuyuladigan bu masalani ko'ramiz.
Masala shartiga binoan bizga bir nechta elementlardan tashkil topgan butun sonli massiv berilgan.
Massivda bitta elementdan tashqari qolgan barchasi ikki martadan qatnashgan. Shu bir marta qatnashgan elementni topish talab qilinmoqda.
Masalan: [3,2,3,1,1] da natija 2 chunki u bir marta qatnashadi.
Chegaraga etibor bersak 1<=array.length <= 3 * 10 ^4
Demak eng sodda yechim sifatida brute force - yane perebor qilish miyaga keladi.
Yane har bitta elementni ikkinchisini topamiz agar topmasak demak shu elementni qaytaramiz.
Yane
1) Oddiy brute force yechim
Lekin Dict (Map) yane lugat malumotlar tuzilmasi ham mavjud.
Shu asosida kalid(key) ni elementni olsak qiymat(value) sifatida shu element
nechi marta qatnashganini olamiz.
map ni Hash ga asoslangan versiyasidan foydalanmoqdamiz. Demak
unga element qushish O(1) (O'rtacha)
Umumiy O(array.length) + asimptotika (yane amallar soni)
lekin Xotira jihatidan biz ortiqcha yana array.length ta element egalladik.
Xush shu oddiy masalani maksimal optimizatsiya qilsak buladimi?
Albatta bo'ladi.
Binar amallar haqida hammamizni xabarimiz bulsa kerak.
Ularni ichida garoib XOR (Qatiy Mantiqiy yoki) amali mavjud.
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0
Binar XOR jadvali yuqorida keltirilgan. Agar unga etibor bersak bir xil holatda 0 har xil bulgan holatda esa 1 kelib chiqmoqda.
Agar sonlar ustida bajarsak chi?
Masalan 12 va 12 ikkalasi ustida XOR bajarsak
1100 (12)
XOR
1100 (12)
-----------
0000 (Natija har doim 0)
Demak natija 0 endi etibor bering. Agar 0 bilan biror sonni ustida XOR bajarsakchi?
100 (4)
XOR
000 (0)
-----------
100 (4)
Natija sonni uzi.
Shuning uchun massivdagi har bir element ustidan bu amalni bajarsak bir xil elementlar bir birini 0 ga tenglashtiradi.
Natijada faqat yolgiz (SINGLE NUMBER) qoladi.
Bu yechim har tomonlama yaxshi. Ham ortiqcha xotira yuq. Ham yechim O(array.length)
Bir qarashda juda oson tuyuladigan bu masalani ko'ramiz.
Masala shartiga binoan bizga bir nechta elementlardan tashkil topgan butun sonli massiv berilgan.
Massivda bitta elementdan tashqari qolgan barchasi ikki martadan qatnashgan. Shu bir marta qatnashgan elementni topish talab qilinmoqda.
Masalan: [3,2,3,1,1] da natija 2 chunki u bir marta qatnashadi.
Chegaraga etibor bersak 1<=array.length <= 3 * 10 ^4
Demak eng sodda yechim sifatida brute force - yane perebor qilish miyaga keladi.
Yane har bitta elementni ikkinchisini topamiz agar topmasak demak shu elementni qaytaramiz.
Yane
1) Oddiy brute force yechim
n=array.length
i=0..n-1
j=i..n
gacha agar array[i] == array[j] bulsa belgilab olamiz
oxirida shu belgiga asoslanib yo davom etamiz yoki shu joyda tuxtatib ekranga chop etamiz.
Lekin Dict (Map) yane lugat malumotlar tuzilmasi ham mavjud.
Shu asosida kalid(key) ni elementni olsak qiymat(value) sifatida shu element
nechi marta qatnashganini olamiz.
class Solution {
public:
int singleNumber(vector<int>& nums)
{
unordered_map<int,int> num;
for (auto i:nums)
{
num[i]++;
}
for(auto i:num)
{
if(i.second==1)
return i.first;
}
return -1;
}
};
map ni Hash ga asoslangan versiyasidan foydalanmoqdamiz. Demak
unga element qushish O(1) (O'rtacha)
Umumiy O(array.length) + asimptotika (yane amallar soni)
lekin Xotira jihatidan biz ortiqcha yana array.length ta element egalladik.
Xush shu oddiy masalani maksimal optimizatsiya qilsak buladimi?
Albatta bo'ladi.
Binar amallar haqida hammamizni xabarimiz bulsa kerak.
Ularni ichida garoib XOR (Qatiy Mantiqiy yoki) amali mavjud.
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0
Binar XOR jadvali yuqorida keltirilgan. Agar unga etibor bersak bir xil holatda 0 har xil bulgan holatda esa 1 kelib chiqmoqda.
Agar sonlar ustida bajarsak chi?
Masalan 12 va 12 ikkalasi ustida XOR bajarsak
1100 (12)
XOR
1100 (12)
-----------
0000 (Natija har doim 0)
Demak natija 0 endi etibor bering. Agar 0 bilan biror sonni ustida XOR bajarsakchi?
100 (4)
XOR
000 (0)
-----------
100 (4)
Natija sonni uzi.
Shuning uchun massivdagi har bir element ustidan bu amalni bajarsak bir xil elementlar bir birini 0 ga tenglashtiradi.
Natijada faqat yolgiz (SINGLE NUMBER) qoladi.
class Solution {
public:
int singleNumber(const std::vector<int>& nums) {
int xorr = 0;
for (const auto& num : nums) {
xorr ^= num;
}
return xorr;
}
};
Bu yechim har tomonlama yaxshi. Ham ortiqcha xotira yuq. Ham yechim O(array.length)
LeetCode
Single Number - LeetCode
Can you solve this real interview question? Single Number - Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra…
You must implement a solution with a linear runtime complexity and use only constant extra…
⚡15👍5
#include <iostream>
#include <vector>
#include <string>
class Quiz {
private:
std::vector<std::pair<std::string, std::string>> questions;
int score = 0;
public:
Quiz() {
questions = {
{"What is 2 + 2?", "4"},
{"What is the capital of France?", "Paris"},
{"Who wrote '1984'?", "George Orwell"}
};
}
void runQuiz() {
for (const auto& [question, answer] : questions) {
std::cout << question << " ";
std::string userAnswer;
std::getline(std::cin, userAnswer);
if (userAnswer == answer) {
score++;
}
}
std::cout << "You scored " << score << " out of " << questions.size() << "!\n";
}
};
int main() {
Quiz quiz;
quiz.runQuiz();
return 0;
}
🔥4🥰3👍2🆒2
Sizningcha yuqoridagi kod SOLID ning qaysi prinsipini buzmoqda?
Anonymous Quiz
41%
S — Single Responsibility Principle
41%
I — Interface Segregation Principle
18%
L — Liskov Substitution Principle
⚡1🔥1👌1
Algo Vision
#include <iostream> #include <vector> #include <string> class Quiz { private: std::vector<std::pair<std::string, std::string>> questions; int score = 0; public: Quiz() { questions = { {"What is 2 + 2?", "4"}, {"What…
SRP — Single Responsibility Principle
Yane bitta component bitta vazifada bo'lishi kerak.
Agar bizning componentimiz sinf bulsa demak u bitta vazifa uchun javobgar bulishi kerak.
Lekin component faqatgina sinf emas balki funksiya va shunga o'xshashlar ham bo'lishi mumkin.
Kodda Quiz sinfi ham savollar tuzilishiga
ham ularning biznes logikasiga (yane bajarilishiga ) javob bermoqda bu esa SRP ga zid.
Mantiqan fikrlasak bizni jarayonimizni qo'yidagi komponentalarga bo'lsak maqul bo'lar edi.
Question faqat savol uchun.
QuizManager esa asosiy logika uchun
QuizUI esa Natijalar uchun
Yane bitta component bitta vazifada bo'lishi kerak.
Agar bizning componentimiz sinf bulsa demak u bitta vazifa uchun javobgar bulishi kerak.
Lekin component faqatgina sinf emas balki funksiya va shunga o'xshashlar ham bo'lishi mumkin.
Kodda Quiz sinfi ham savollar tuzilishiga
ham ularning biznes logikasiga (yane bajarilishiga ) javob bermoqda bu esa SRP ga zid.
Mantiqan fikrlasak bizni jarayonimizni qo'yidagi komponentalarga bo'lsak maqul bo'lar edi.
#include <iostream>
#include <vector>
#include <string>
class Question {
public:
std::string questionText;
std::string correctAnswer;
Question(const std::string& text, const std::string& answer)
: questionText(text), correctAnswer(answer) {}
};
class QuizManager {
private:
std::vector<Question> questions;
int score = 0;
public:
QuizManager(const std::vector<Question>& q) : questions(q) {}
void runQuiz() {
for (const auto& q : questions) {
std::cout << q.questionText << " ";
std::string userAnswer;
std::getline(std::cin, userAnswer);
if (userAnswer == q.correctAnswer) {
score++;
}
}
}
int getScore() const { return score; }
int getTotalQuestions() const { return questions.size(); }
};
class QuizUI {
public:
static void displayResult(int score, int totalQuestions) {
std::cout << "You scored " << score << " out of " << totalQuestions << "!\n";
}
};
int main() {
std::vector<Question> questions = {
{"What is 2 + 2?", "4"},
{"What is the capital of France?", "Paris"},
{"Who wrote '1984'?", "George Orwell"}
};
QuizManager quizManager(questions);
quizManager.runQuiz();
QuizUI::displayResult(quizManager.getScore(), quizManager.getTotalQuestions());
return 0;
}
Question faqat savol uchun.
QuizManager esa asosiy logika uchun
QuizUI esa Natijalar uchun
✍4👍4🏆4⚡2🔥2
SOLID
Open/Closed Principle
The Open/Closed Principle states that:
Code should be open for extension — new functionality can be added.
Code should be closed for modification — existing code should not be changed.
This ensures code stability and easier maintenance. Instead of changing old code, we add new code.
Below is an example that violates the Open/Closed Principle (OCP). In this example, every time a new type of message is added, the existing code must be modified, which makes it less maintainable and more prone to bugs.
The second example shows a correct implementation of the Open/Closed Principle. Instead of modifying existing code, new behavior is added by extending the base class. This approach makes the code more flexible and easier to maintain.
Remember to write clean and readable code
Open/Closed Principle
The Open/Closed Principle states that:
Code should be open for extension — new functionality can be added.
Code should be closed for modification — existing code should not be changed.
This ensures code stability and easier maintenance. Instead of changing old code, we add new code.
Below is an example that violates the Open/Closed Principle (OCP). In this example, every time a new type of message is added, the existing code must be modified, which makes it less maintainable and more prone to bugs.
The second example shows a correct implementation of the Open/Closed Principle. Instead of modifying existing code, new behavior is added by extending the base class. This approach makes the code more flexible and easier to maintain.
Remember to write clean and readable code
#include <iostream>
#include <string>
// Function that violates OCP by using if-else for each message type
class MessageHandler {
public:
void handle(const std::string& type, const std::string& message) {
if (type == "text") {
std::cout << "Handling text message: " << message << '\n';
} else if (type == "error") {
std::cerr << "Handling error message: " << message << '\n';
} else {
std::cout << "Unknown message type: " << message << '\n';
}
}
};
int main() {
MessageHandler handler;
handler.handle("text", "Hello, World!");
handler.handle("error", "Something went wrong.");
handler.handle("info", "New message type!"); // Adding new types requires modifying the method
return 0;
}
#include <iostream>
#include <string>
#include <memory>
#include <vector>
// Base class that defines the interface
class MessageHandler {
public:
virtual ~MessageHandler() = default;
virtual void handle(const std::string& message) const = 0;
};
// Handler for text messages
class TextMessageHandler : public MessageHandler {
public:
void handle(const std::string& message) const override {
std::cout << "Handling text message: " << message << '\n';
}
};
// Handler for error messages
class ErrorMessageHandler : public MessageHandler {
public:
void handle(const std::string& message) const override {
std::cerr << "Handling error message: " << message << '\n';
}
};
int main() {
std::vector<std::shared_ptr<MessageHandler>> handlers;
handlers.emplace_back(std::make_shared<TextMessageHandler>());
handlers.emplace_back(std::make_shared<ErrorMessageHandler>());
for (const auto& handler : handlers) {
handler->handle("Hello, World!"); // No need to change the existing code
}
return 0;
}
🔥7💯3👍2👌2⚡1❤1
Forwarded from OSON
OSON terminallari orqali xayriya qiling💙
Endi bu juda oson!✅
OSON termanallari yoki mobil ilova orqali masjidlar qurilishiga, nogiron bolalar va mehribonlik uylariga xayriya qilish imkoniyatingiz bor.
OSON - birgalikda yaxshilik qilamiz!🫶
_________
Совершайте благотворительность через терминалы OSON💙
Теперь это очень просто!✅
С помощью терминалов OSON или мобильного приложения вы можете жертвовать на строительство мечетей, для детей с ограниченными возможностями и в дома милосердия.
OSON — творим добро вместе! 🫶
📞 Qo'llab quvvatlash xizmati
Instagram📱 | Telegram 📱 | Facebook 📱
Yuklab olish:
IOS📱 Android 📱
Telegram
Endi bu juda oson!✅
OSON termanallari yoki mobil ilova orqali masjidlar qurilishiga, nogiron bolalar va mehribonlik uylariga xayriya qilish imkoniyatingiz bor.
OSON - birgalikda yaxshilik qilamiz!🫶
_________
Совершайте благотворительность через терминалы OSON💙
Теперь это очень просто!✅
С помощью терминалов OSON или мобильного приложения вы можете жертвовать на строительство мечетей, для детей с ограниченными возможностями и в дома милосердия.
OSON — творим добро вместе! 🫶
Yuklab olish:
IOS
Telegram
Please open Telegram to view this post
VIEW IN TELEGRAM
⚡7🆒3👍2❤1
🚀 Job Opportunity: Senior C++/Java Software Engineer (UZ)
Hello, everyone! 👋 If you're an experienced C++ or Java developer looking for new challenges, I have an exciting opportunity to share! 🎉 DSR Corporation is currently hiring for the role of Senior C++/Java Software Engineer.
For more details and to apply, please visit the link below:
🔗 Senior C++/Java Software Engineer - DSR Corporation
Hello, everyone! 👋 If you're an experienced C++ or Java developer looking for new challenges, I have an exciting opportunity to share! 🎉 DSR Corporation is currently hiring for the role of Senior C++/Java Software Engineer.
For more details and to apply, please visit the link below:
🔗 Senior C++/Java Software Engineer - DSR Corporation
⚡9👍1🌭1
Agar shunaqalar qulingizga tushsa ozingizni maksimal bilmaslikka olib ularni imkon qadar vaqtini bekorga sarflashlariga majbur qiling.
Agar kimdir gaplarimni tushunmagan bulsa.
Bumday mosheniklarga hech qachon ishonmang. Hech qachon dasturni hoki shubhada bulgan faylni ochmang. Ozingiz va yaqinlaringizi asrang.
Ikkita narsani unutmang.
Ishlamasiz sizga birov pul bermaydi( sovgalar asosidagi mosheniklar)
Tanish bulmasiz sizga birov shunday uz uzidan yordam qilmaydi yane foizsiz kredit .... oddiy muslima va musulmonlarimiz juda kop shunga tushishgan
Agar kimdir gaplarimni tushunmagan bulsa.
Bumday mosheniklarga hech qachon ishonmang. Hech qachon dasturni hoki shubhada bulgan faylni ochmang. Ozingiz va yaqinlaringizi asrang.
Ikkita narsani unutmang.
Ishlamasiz sizga birov pul bermaydi( sovgalar asosidagi mosheniklar)
Tanish bulmasiz sizga birov shunday uz uzidan yordam qilmaydi yane foizsiz kredit .... oddiy muslima va musulmonlarimiz juda kop shunga tushishgan
⚡9👍5👨💻1
Bir ajoib va menimcha hammaga tezda tushunarli buladigan masalani sizlar bilan bo'lishmoqchiman.
Menimcha hamma faktorial haqida xabari bor.
n! (yoki n faktorial) bu 1 dan n gacha bo'lgan barcha sonlar ko'paytmasi.
Masalan:
4!=1*2*3*4
5!=1*2*3*4*5
........................
Demak n! = 1*2*3*4*....*n (0!=1 deb olishadi odadta)
va albatta hamma raqamdan sonni farqiga boradi degan umiddaman.
___________________________________________________________________________
Agar doskada d raqamini n! marotaba yozsak u qaysi toq raqamlarga bo'linadi?(Bu codeforces sodda masalalaridan biri)
n = 1...10^9 gacha
Masalan d=1 n=3
3!=1*2*3=6
111111-shu son qaysi toq raqamlarga bo'linadi?
toq raqamlar 1 3 5 7 9
shu lardan 1 3 7 ga bulinadi.
Algoritmingizni izohlarda qoldiring.
#Logic
#Math
Menimcha hamma faktorial haqida xabari bor.
n! (yoki n faktorial) bu 1 dan n gacha bo'lgan barcha sonlar ko'paytmasi.
Masalan:
4!=1*2*3*4
5!=1*2*3*4*5
........................
Demak n! = 1*2*3*4*....*n (0!=1 deb olishadi odadta)
va albatta hamma raqamdan sonni farqiga boradi degan umiddaman.
___________________________________________________________________________
Agar doskada d raqamini n! marotaba yozsak u qaysi toq raqamlarga bo'linadi?(Bu codeforces sodda masalalaridan biri)
n = 1...10^9 gacha
Masalan d=1 n=3
3!=1*2*3=6
111111-shu son qaysi toq raqamlarga bo'linadi?
toq raqamlar 1 3 5 7 9
shu lardan 1 3 7 ga bulinadi.
Algoritmingizni izohlarda qoldiring.
#Logic
#Math
⚡2👍2
Algo Vision
Bir ajoib va menimcha hammaga tezda tushunarli buladigan masalani sizlar bilan bo'lishmoqchiman. Menimcha hamma faktorial haqida xabari bor. n! (yoki n faktorial) bu 1 dan n gacha bo'lgan barcha sonlar ko'paytmasi. Masalan: 4!=1*2*3*4 5!=1*2*3*4*5 .....…
en:
I want to share with you an interesting problem that I think will be easy for everyone to understand.
I believe everyone is familiar with the concept of a factorial.
n! (or n factorial) is the product of all numbers from 1 to n.
For example:
4! = 1 × 2 × 3 × 4
5! = 1 × 2 × 3 × 4 × 5
...
So, n! = 1 × 2 × 3 × 4 × ... × n (and by convention, 0! = 1).
Hopefully, everyone understands this so far.
The problem:
If the digit d is written n! times on the board, which odd numbers will it be divisible by?
(This is one of the simple problems from Codeforces.)
Given:
n = 1...10^9
Example:
d = 1, n = 3
3! = 1 × 2 × 3 = 6
Writing 1 6 times gives us 111111. Which odd numbers is this divisible by?
Odd numbers: 1, 3, 5, 7, 9
From these, 111111 is divisible by 1, 3, and 7.
Leave your algorithm in the comments!
#math
#logick
I want to share with you an interesting problem that I think will be easy for everyone to understand.
I believe everyone is familiar with the concept of a factorial.
n! (or n factorial) is the product of all numbers from 1 to n.
For example:
4! = 1 × 2 × 3 × 4
5! = 1 × 2 × 3 × 4 × 5
...
So, n! = 1 × 2 × 3 × 4 × ... × n (and by convention, 0! = 1).
Hopefully, everyone understands this so far.
The problem:
If the digit d is written n! times on the board, which odd numbers will it be divisible by?
(This is one of the simple problems from Codeforces.)
Given:
n = 1...10^9
Example:
d = 1, n = 3
3! = 1 × 2 × 3 = 6
Writing 1 6 times gives us 111111. Which odd numbers is this divisible by?
Odd numbers: 1, 3, 5, 7, 9
From these, 111111 is divisible by 1, 3, and 7.
Leave your algorithm in the comments!
#math
#logick
⚡3👍2
#include <iostream>
#include <cmath>
bool isPrime(int number) {
if (number <= 1) {
return false; // 0 and 1 are not prime numbers
}
if (number == 2) {
return true; // 2 is a prime number
}
if (number % 2 == 0) {
return false; // Even numbers greater than 2 are not prime
}
for (int i = 3; i <= std::sqrt(number); i += 2) {
if (number % i == 0) {
return false; // Divisible by a number other than 1 and itself
}
}
return true;
}
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (isPrime(number)) {
std::cout << number << " is a prime number.\n";
} else {
std::cout << number << " is not a prime number.\n";
}
return 0;
}
Code Review
Bu yerda tub sonni aniqlaydigan sodda kod berilgan.
Bu kodni har tomonlama optimizatsiya qilsa bo'ladi!
Fikringizni izohlarda qoldiring
This code can be optimized in many ways.
What are your suggestions? Share your thoughts in the comments! 🚀
😐3
⚡3
Algo Vision
Qaysi OS dan ko'proq foydalanasiz
Stream utkazsam qaysi mavzuda bulishini xohlaysz.
Algoritmlar
Productiv C++
Algoritmlar
Productiv C++
⚡5
Sieve of Eratosthenes in C++: Spot the Errors and Improve the Code!
Here's an implementation of the "Sieve of Eratosthenes" algorithm in C++.
At first glance, the code seems functional, but it contains a few mistakes and areas for improvement. This is a great opportunity for you to practice your code review skills!
Task: Spot the issues in the code and suggest how it can be optimized or written more effectively. Share your thoughts in the comments!
Qo'yida sizga "Eratosfen g'alviri" nomli tub sonlarni maksimal tez aniqliydigan algoritm berilgan.
Algoritm goyasi kodda tuliq ifodanalangna lekin bazi bir kichik xatolar va kamchiliklar mavjud.
Bazi kamchiliklar til bilan boglangan bazilar esa yo'q
Xo'sh siz algoritmni dasturiy shaklni yanada optimal ko'rinishga keltirish uchun qanday fikr bera olasz?
Fikringizni izohlarda qoldiring.
#review
#algorithm
Here's an implementation of the "Sieve of Eratosthenes" algorithm in C++.
At first glance, the code seems functional, but it contains a few mistakes and areas for improvement. This is a great opportunity for you to practice your code review skills!
Task: Spot the issues in the code and suggest how it can be optimized or written more effectively. Share your thoughts in the comments!
Qo'yida sizga "Eratosfen g'alviri" nomli tub sonlarni maksimal tez aniqliydigan algoritm berilgan.
Algoritm goyasi kodda tuliq ifodanalangna lekin bazi bir kichik xatolar va kamchiliklar mavjud.
Bazi kamchiliklar til bilan boglangan bazilar esa yo'q
Xo'sh siz algoritmni dasturiy shaklni yanada optimal ko'rinishga keltirish uchun qanday fikr bera olasz?
Fikringizni izohlarda qoldiring.
#include <iostream>
#include <vector>
void sieveOfEratosthenes(int n) {
std::vector<bool> primes(n); // Using a vector to store prime numbers
for (int i = 0; i < n; i++) {
primes[i] = true; // Initialize all numbers as prime
}
primes[0] = primes[1] = false; // 0 and 1 are not prime numbers
for (int p = 2; p < n; p++) { // Iterating up to n instead of sqrt(n)
if (primes[p]) { // If the number is still marked as prime
for (int i = p * p; i < n; i += p) { // Start marking multiples from p * p
primes[i] = false; // Mark multiples as non-prime
}
}
}
// Print prime numbers
std::cout << "Prime numbers up to " << n << ": ";
for (int i = 2; i < n; i++) {
if (primes[i]) {
std::cout << i << " ";
}
}
std::cout << std::endl;
}
int main() {
int n = 50; // Fixed value for testing
sieveOfEratosthenes(n);
return 0;
}
#review
#algorithm
👍9
Algo Vision
#include <iostream>
#include <cmath>
bool isPrime(int number) {
if (number <= 1) {
return false; // 0 and 1 are not prime numbers
}
if (number == 2) {
return true; // 2 is a prime number
}
if (number % 2 == 0) {
return false; // Even numbers greater than 2 are not prime
}
for (int i = 3; i <= std::sqrt(number); i += 2) {
if (number % i == 0) {
return false; // Divisible by a number other than 1 and itself
}
}
return true;
}
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (isPrime(number)) {
std::cout << number << " is a prime number.\n";
} else {
std::cout << number << " is not a prime number.\n";
}
return 0;
}
#include <cmath>
bool isPrime(int number) {
if (number <= 1) {
return false; // 0 and 1 are not prime numbers
}
if (number == 2) {
return true; // 2 is a prime number
}
if (number % 2 == 0) {
return false; // Even numbers greater than 2 are not prime
}
for (int i = 3; i <= std::sqrt(number); i += 2) {
if (number % i == 0) {
return false; // Divisible by a number other than 1 and itself
}
}
return true;
}
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (isPrime(number)) {
std::cout << number << " is a prime number.\n";
} else {
std::cout << number << " is not a prime number.\n";
}
return 0;
}
#include <iostream>
#include <cmath>
constexpr bool isPrime(int number) {
if (number <= 1) return false;
if (number <= 3) return true;
if (number % 2 == 0 || number % 3 == 0) return false;
for (int i = 5; i * i <= number; i += 6) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
}
return true;
}
int main() {
int number;
std::cin >> number;
for(int i = 1; i <= number; i++){
if(isPrime(i))
std::cout << i << " ";
}
return 0;
}
Bu review qilingan variantlardan biri.
Xo'sh endi siz isbotlangchi nega bu har doim to'gri ishlashi kerak?
Umumiy olganda algoritm O(\|N)
Review qilganimizda imkon qadar ortiqcha if else lardan va bir const narsani qayta qayta hisoblashdan (sqrt(N))
voz kechishimiz kerak. Albatta zamonaviy C++ kompilerlar juda aqlli ular bu amallarni maksimal bajarashida (Lekin bu yerda umumiy dasturlash tiliga boglanmasdan olingan)
⚡8
Algo Vision
#include <iostream> #include <cmath> constexpr bool isPrime(int number) { if (number <= 1) return false; if (number <= 3) return true; if (number % 2 == 0 || number % 3 == 0) return false; for (int i = 5; i * i <= number; i += 6) { …
Va albatta bitta narsaga etibor berilishi kerak
C++ dasturlashda consteval va constexpr tushunchalar bor.
Bu kalid so'zlar bilan ifodalangan ifoda o'zgaruvchi yoki funksiyalar compile vaqtda hisoblanishi mumkin.
Bu degani dasturni ishga tushurganimizda uni hisoblash uchun alohida vaqt talab qilinmaydi.
Yuqoridagi kodda bu narsa ishlaymaydi va hech qanday effekt bermaydi.
Chunki biz funksiyani non-const qiymat bilan chaqiriyapmiz.
Bu holda barcha amallar compilyatsiya jarayonida bajariladi
C++ dasturlashda consteval va constexpr tushunchalar bor.
Bu kalid so'zlar bilan ifodalangan ifoda o'zgaruvchi yoki funksiyalar compile vaqtda hisoblanishi mumkin.
Bu degani dasturni ishga tushurganimizda uni hisoblash uchun alohida vaqt talab qilinmaydi.
Yuqoridagi kodda bu narsa ishlaymaydi va hech qanday effekt bermaydi.
Chunki biz funksiyani non-const qiymat bilan chaqiriyapmiz.
int main() {
constexpr int number = 15555;//bu ham compile timeda hisoblanadi
if(isPrime(number))
std::cout <<"Tub" << "";
return 0;
}
Bu holda barcha amallar compilyatsiya jarayonida bajariladi
⚡6🆒1
Which of the following expressions always correctly checks if the number N is even?
Qo'yidagi qaysi ifoda sonni juftligini doimo to'gri tekshiradi
Qo'yidagi qaysi ifoda sonni juftligini doimo to'gri tekshiradi
Anonymous Poll
28%
N & 1 == 0
73%
N % 2 == 0
13%
N | 1 == 0
28%
(N>>1)<<1==N
😨4
Yuqoridagi kod qanday natija qayataradi. (Queue bu navbat malumoatlar strukturas)
Anonymous Quiz
33%
1
28%
2
17%
3
21%
Compile Error