n-তম أغলি নাম্বার বের করতে হবে। أغলি নাম্বার হলো সেই সংখ্যাগুলো যাদের প্রাইম ফ্যাক্টর শুধু ২, ৩ আর ৫। ১০-ম أغলি নাম্বার ১২, কারণ প্রথম কিছু أغলি নাম্বার: ১, ২, ৩, ৪, ৫, ৬, ৮, ৯, ১০, ১২।
সমাধানের ধাপগুলো:
vআকারn+1-এর অ্যারে বানান।- যদি
n == 1, ১ ফেরত দিন। two := 2, three := 3, five := 5,twoIdx := 2, threeIdx := 2, fiveIdx := 2i = 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