Convert PARI program to C++ -
i found sequence of interest in oeis , want generate same sequence in c++ programming competition solution working on.
however hit roadblock understanding how program given in sequence page works.
here program given in page -
(pari) test(n)= {m=n; forprime(p=2, 5, while(m%p==0, m=m/p)); return(m==1)} for(n=1, 500, if(test(n), print1(n", "))) (pari) a(n)=local(m); if(n<1, 0, n=a(n-1); until(if(m=n, forprime(p=2, 5, while(m%p==0, m/=p)); m==1), n++); n) (pari) list(lim)={ lim\=1; my(v=list(), s, t); for(i=0, log(lim+.5)\log(5), t=5^i; for(j=0, log(lim\t+.5)\log(3), s=t*3^j; while(s <= lim, listput(v, s); s <<= 1; ) ) ); vecsort(vec(v)) };
i found out pari is, unable convert program c++. suggestions me generate same sequence in c++ appreciated.
i tried generate sequence in c++ following code snippet. think missing numbers in between fail few tests in online ide.
for(int = 0; < 16; i++) { for(int j = 0; j < 15; j++) { for(int k = 0; k < 12; k++) { std::cout<<pow(2,i)*pow(3,j)*pow(5,k)<<std::endl; } } }
i chose 16, 15 , 12 limits because otherwise result value overflows long variable type.
you have 3 programs here, each of serve different purposes.
the first checks if number 5-smooth. divides 2, 3, , 5 until can't more, , tests if what's left 1.
the second generates ''n''th 5-smooth number. uses same idea first, testing each number in range. inefficient!
the third generates 5-smooth numbers given bound.
i'm going assume third want, because seems applicable situation. (it helps author of program.)
#include <iostream> #include <vector> #include <algorithm> int main(void); std::vector<long> smooth(long lim); int main(void) { long lim = 1000; std::vector<long> v = smooth(lim); std::cout << "5-smooth numbers " << lim << ": "; (std::vector<long>::iterator = v.begin(); != v.end(); it++) { std::cout << *it << ", "; } std::cout << "\n"; return 0; } std::vector<long> smooth(long lim) { std::vector<long> v = {}; (long t = 1; t <= lim; t*=5) { (long s = t; s <= lim; s*=3) { (long n = s; n <= lim; n*=2) { v.push_back(n); } } } std::sort(v.begin(), v.end()); return v; }
this isn't line-by-line conversion, of course; example, didn't use logarithms since exact logarithms aren't built-in c++ pari. it's pretty fast, finds 5-smooth numbers 1,844,674,407,370,955,161 (the highest can on 64-bit machine) in fraction of second.
Comments
Post a Comment