কম্পিউটার টিউটোরিয়াল

C++-এ أغলি নাম্বার II


n-তম أغলি নাম্বার বের করতে হবে। أغলি নাম্বার হলো সেই সংখ্যাগুলো যাদের প্রাইম ফ্যাক্টর শুধু ২, ৩ আর ৫। ১০-ম أغলি নাম্বার ১২, কারণ প্রথম কিছু أغলি নাম্বার: ১, ২, ৩, ৪, ৫, ৬, ৮, ৯, ১০, ১২।

সমাধানের ধাপগুলো:

  • v আকার n+1-এর অ্যারে বানান।
  • যদি n == 1, ১ ফেরত দিন।
  • two := 2, three := 3, five := 5, twoIdx := 2, threeIdx := 2, fiveIdx := 2
  • i = 2 থেকে n পর্যন্ত:
    • curr := min(two, three, five)
    • v[i] := curr
    • যদি curr == two, two := v[twoIdx]*2, twoIdx++
    • যদি curr == three, three := v[threeIdx]*3, threeIdx++
    • যদি curr == five, five := v[fiveIdx]*5, fiveIdx++
  • v[n] ফেরত দিন।

উদাহরণ (C++)

#include <bits/stdc++.h> using namespace std; class Solution {    public:    int nthUglyNumber(int n) {       vector <int> v(n + 1);       if(n == 1){          return 1;       }       int two = 2, three = 3, five = 5;       int twoIdx = 2;       int threeIdx = 2;       int fiveIdx = 2;       for(int i = 2; i <= n; i++){          int curr = min({two, three, five});          v[i] = curr;          if(curr == two){             two = v[twoIdx] * 2;;             twoIdx++;          }          if(curr == three){             three = v[threeIdx] * 3;             threeIdx++;          }          if(curr == five){             five = v[fiveIdx] * 5;             fiveIdx++;          }       }       return v[n];    } }; main(){    Solution ob;    cout << (ob.nthUglyNumber(10)); }

ইনপুট

10

আউটপুট

12

  1. Frugal সংখ্যা চেক করা (C++)

  2. C++ দিয়ে পেন্টাটপ (Pentatope) সংখ্যা বের করা

  3. C++-এ অসুন্দর সংখ্যা (Ugly Number)

  4. C++-এ অ্যাডাম সংখ্যা (Adam Number) চেক করার পদ্ধতি