

That is interesting.
"The clue train passed his station without stopping."  John Simmons / outlaw programmer
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks"  Pete O'Hanlon





It works, but it's inefficient.
/ravi





Ian Uy wrote: Yup, for some reason it did threw the right answers.
I think if you're aiming for the ACM ICPC then you should try to understand why it gives the correct answers (and at first glance it looks as if it should). The fact that i may not be prime actually doesn't matter (well except for efficiency concerns).
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."





Hi,
one remark: you should replace the if(){} construct by a while(){} and drop the i;
that way your code is more readable, and you can now more easily reduce the divisor candidates
(say to only 2 and odd numbers, or just primes, or whatever else has already been suggested).





Robert.C.Cartaino wrote: As a college student, you really should be able to do this. It's basic math.
To be fair, my bet is 99% of college students don't know (or care) how to do this, along with 99% of the rest of the world.
I'm about to finish up my second engineering degree, and prime numbers have not been brought up once during the 5 years i've been here.





MarkBrock wrote: my bet is 99% of college students don't know (or care) how to do this, along with 99% of the rest of the world.
I agree. Maybe a bit more than 99%, like 99.9999%
"The clue train passed his station without stopping."  John Simmons / outlaw programmer
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks"  Pete O'Hanlon





MarkBrock wrote: To be fair, my bet is 99% of college students don't know (or care) how to do this, along with 99% of the rest of the world.
You must have been taught how at junior school, though
I know, since my son has this in his Math book.





ChandraRam wrote: You must have been taught how at junior school, though
Yeah, I was.
Sit down and watch the TV show "Are you smarter than a 5th grader". Unless you've got better memory than an elephant, I bet you can't answer most of the questions .





You do not need to divide by all numbers, only by primes. If the number is evenly divided by a prime, then keep dividing by that prime until the result leaves a remainder, then go to the next prime. There exists (google primes) a site on which there is a list of the primes for the first million numbers, the second million numbers ... to the first 15 million numbers.
Dave Augustine.





Member 4194593 wrote: You do not need to divide by all numbers, only by primes.
... and, if we are optimizing, your forloop does not need to run all the way up to InputCase . You only need to check for divisibility of numbers up to the square root of InputCase .





I see. I'll apply both suggestions.
That's why its so slow at 20!.
It is said that the most complex structures built by mankind are software systems. This is not generally appreciated because most people cannot see them. Maybe that's a good thing because if we saw them as buildings, we'd deem many of them unsafe.





Ian Uy wrote: That's why its so slow at 20!.
There are easier ways of factorizing 20!
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."





A possible solution would be as follows:
void prime_factors(unsigned int n, std::deque<std::pair<unsigned int,unsigned int>>& factor_list)
{
factor_list.clear();
unsigned int upper_bound = ::floor(std::sqrt(n));
unsigned int i = 2;
while(i <= upper_bound)
{
std::pair<unsigned int, unsigned int> current_factor(i,0);
while(0 == (n % i))
{
n /= i;
++current_factor.second;
}
if (current_factor.second > 0)
{
factor_list.push_back(current_factor);
}
++i;
}
}
The primefactors will be in the deque, the first of each element is the factor and the second is the recurrence count of the factor.
[updated]





[edit] since Arash has completely changed the code in his previous post, this appears somewhat out of context [/edit]
I think this is an example of misguided optimization. Whilst Ian Uy's example looks inefficient
int main()
{
int InputCase;
cin >> InputCase;
for(int i=2;i<=InputCase;i++)
{
if(InputCase%i==0)
{
cout << i;
InputCase/=i;
i;
}
}
return 0;
}
all he is doing each iteration is testing
if(InputCase%i==0)
In order to avoid these "unnecessary" tests, you are testing each n as
if (n % 2 == 0) n++;
while(!is_prime(n)) { ++n; }
The function is_prime(n) will involve much more overhead than the original code, and it doesn't matter that 'i' may not be prime.
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."
modified on Saturday, October 18, 2008 11:35 PM





Hi Peter,
I agree.
Some improvements are possible, but they do not involve adding method calls:
1. replacing if(){} by while(){} and dropping the i;
then changing the for loop so it starts with 3 and increments by 2 or by 2 and 4 alternating
(make sure to test 2 itself also)
2. use multiple (say two) threads, assuming a Core Duo or something similar.





Hi Luc,
True. The most important thing he should do is limit the testing to sqrt(N).
To factorise a number N, you need to test up to sqrt(N), and there are approximately
sqrt(N)/log(sqrt(N)) primes to test. For example, to factorise 1,000,000 you only need to test the 168 primes less than 1000, or 16.8% of the numbers less than 1000.
Using the simple algorithm you test 100% of the numbers less than sqrt(N):
if you eliminate the multiples of 2 you are down to testing about 50%
then eliminating the multiples of 3 drops you to testing 33.3%
then eliminating the multiples of 5 drops you to testing 26.7%
and so on.
the first few are probably worthwhile as you point out, but you then rapidly get in to diminishing returns, and may easily get to the stage where it is not worth the effort to save the time of the line
if(InputCase%i==0)
I don't think multiple threads are worthwhile until you go past 32 bit arithmetic (even the simplest algorithm only has 2^16 tests to do).
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."
modified on Sunday, June 29, 2008 10:10 PM





cp9876 wrote: The most important thing he should do is limit the testing to sqrt(N).
I believe this is not correct, assume you have an x composed from 2p where p is a prime, in this case it is clear that in certain circumstance sqrt(x) can be less than p (eg: 15838 = 7919 * 2, where 7919 > sqrt(15838)), for primal testing the sqrt(n) bound is ok, however its not suitable for the upper bound in this problem.





Arash Partow wrote: I believe this is not correct, assume you have an x composed from 2p where p is a prime, in this case it is clear that in certain circumstance sqrt(x) can be less than p (eg: 15838 = 7919 * 2, where 7919 > sqrt(15838)), for primal testing the sqrt(n) bound is ok, however its not suitable for the upper bound in this problem.
He's studying for the ACM competition  I don't want to spoon feed him! He can limit his testing to sqrt(N) but he has to modify his algorithm slightly for when InputCase is not 1 at the end.
In the example you give, he only needs to test until floor(sqrt(15838))=125, he will have only found 2 as a factor and InputCase will be 7919 after the 124 tests. He can then conclude the the remaining value in InputCase is the remaining prime factor. This is much more efficient than testing the remaining 15,703 factors.
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."





cp9876 wrote: This is much more efficient than testing the remaining 15,703 factors.
true.





you're right, as long as one divides by the current number until the remainder is nonzero they will have taken out all of the multipleoffactors as well, no need to explicitly only test/divide by primes.
good catch!





Hello,
i have set of 2D points and i want to offset with a given distance (like offset command in AutoCAD)
i do not know how to deal with corners. i have searched on Internet, there are advanced methods like straight skeletons etc. but my polyline is not self crossing and no holes in it.
Is there any simple method? any references?
Best Regards.
Bekir





Why can't you just iterate through the points and add your offset to each one? It seems like this should translate the corners along with everything else.






beko wrote: Just translating the edges with the offset distance will not work.
Why not?
beko wrote: I have found an algorithm not tested throughly, but it is working at least for my very simple 3 points polyline test
What kind of test you did?
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
 Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
 Iain Clarke





Hello,
At the end, it is a translation however it must be implemented with respect to the normals, as far as i read through if it is a parametric curve then it is rather complicated. If you like to see how much it can further get complicated, you can have a look at the link below.
http://timeguy.com/cradekfiles/emc/liu2007_line_arc_offset.pdf[^]
for the test, i have just created a polyline with three points and used the algorithm from Eduardo in my earlier reply, and compared it with AutoCAD output
Best Regards.





That paper seems to give a good description of how to do it. It's complicated, you will have lots of cases  you'll just have to get used to it.
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."





There is no simple solution to this problem, the best known general solution, is to create capsules between consecutive point pairs of your polyline where the capsule width is the offset, then union the capsule outlines. The capsule may be centered around the edge or it may be biased towards one side of the edge it is really up to the end requirement. For the union operation use something like Alan Murta's Generic Polygon Clipper library.
If you know your polyline is enclosed and represents a convex polygon, then simply calculate the centroid, then offset each edge by the product of the desired offset amount and the vector composed of the midpoint of the edge at hand minus the centroid.
A simple example can be found here:
http://www.codeproject.com/KB/recipes/Wykobi.aspx





Thank you for the all answers,
I will have a look at it.
Best Regards.





Hi all. I've been working on a model in Excel that I'm considering porting into C/C++. I've been using the "Goal Seek" function in Excel to find a value in one cell that causes the results in another cell to equal some target value.
Is there an existing numerical recipe/algorithm to perform a similar function in C without reinventing the wheel?
Thanks for any help!





Not in C/C++, but this is a custom implementation in VB:
http://www.bmsltd.ie/DLCount/DLCount.asp?file=GoalSeek.zip[^]
Goal seeking is based on linear interpolation, perhaps you can adapt the VB code to C++?
I'm not too familiar with COM, etc. so I don't know the details but I do know that you can make calls to Excel from C++, maybe you can call the Excel Goal Seek function using COM (by loading the Excel .dll)?





"...but I do know that you can make calls to Excel from C++..."
Well, THAT would solve my problem! I've been doing a lot of processing in Excel (nicer, because I can see the numbers all laid out), then saving data to a text file, reading it into my C program and continuing my model that way. If I could just make calls right into a spreadsheet I could save myself a lot of dumb grunt labor. I'll check into that. Thanks!





Here[^] is a Microsoft knowledgebase article that provides some explanation. I think you have to use MFC to do it.
If you want to use Managed C++, here's a nice CP article:
Link[^].
I don't know a whole lot about COM, etc...so you might want to try asking for more details in the C++ forums here. Somebody can probably give you more assistance there.





KimN wrote: Is there an existing numerical recipe
There is a famous book called "Numerical Recipes", the original editions are available online for free. See here[^]. I think you need some adobe plugin to view the books  it is well worthwhile.
What you are interested in is optimisation of functions. The way this is typically done is you define a function that you want to minimize, e.g.
double func(double* x)
which takes N variables in the array 'x' and returns a single value. An optimization routine will attempt to find the values of 'x' that minimize the function. A very simple workhorse is called the downhill simplex method in multidimensions, but to you it is simply a function Amoeba to which you pass mainly a pointer to your function, the number of variables and starting values.
If you want to solve f(x) = c, make func(x) = (f(x)  c)^2
You will find a listing for amoeba in section 10.4 of Numerical Recipes in C.
If you know more about the function you are trying to minimize then there are probably better routines available, but I'd suspect that amoeba will work as well as excel (and be much faster in native code).
Peter
"Until the invention of the computer, the machine gun was the device that enabled humans to make the most mistakes in the smallest amount of time."





Good answer, nicely explained.





i have a mathematical function,example x^2+sin(x),but it is String.i want it is mathematical function,it can return value float
leo





nta_3886 wrote: i want it is mathematical function,it can return value float
Ok.
"A good athlete is the result of a good and worthy opponent."  David Crow
"To have a respect for ourselves guides our morals; to have deference for others governs our manners."  Laurence Sterne





use a stack to convert the formula into Reverse Polish Notation (RPN). Then evaluate the RPN version. You can find many examples of how to do both steps of this via google.

If you view money as inherently evil, I view it as my duty to assist in making you more virtuous.





dan neely wrote: use a stack to convert the formula into Reverse Polish Notation (RPN). Then evaluate the RPN version. You can find many examples of how to do both steps of this via google.
Semiontopic... I just found my code for this from Pascal class back in the 80's. I used it on my first job to build an RPN based spreadsheet program in RPG II.
_________________________
Asu no koto o ieba, tenjo de nezumi ga warau.
Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)





a lot of work
Russell





If you are using the .net Framework then you can compile that into a method in a temporary assembly and execute it as normal code.
I'm sure you can find a sample about that in the WWW.
^^^^^
no risk no funk ................... please vote >






If you are using Rexx then
interpret say "string"
Except you first need to write sin(x) and other functions you use in Rexx. You also need to use Rexx rules for syntax.
Rexx can compile and execute on the fly.
With just a little more detail in dos one might type
rexx math 1.2*4.7
5.64 prints
The file math.cmd contains
/* execute incomming statement */
numeric digits 40
arg cmd
interpret say cmd
It's been a while but saving x to a environment variable or some such is not that hard.
My 40 digit ln() in ln.cmd is
/* ln(x) */
numeric digits 40
arg x
/* prescale to put x into reasonable range */
xp = 0
if x > 2 then do until x < 2
xp = xp + 1
x = x / 2
end
/* now that x <=2 compute ln(x)
method from Abramowitz etal section 4.1.39
ln(2) to 40 places takes 26 loops */
z = x1
val = 0
do t = 26 to 1 by 1
t2z = t*t*z
val = t2z / (t+t+val+1)
val = t2z / (t+t+val)
end
val = z / (val+1)
/* account for prescale */
if xp = 0 then return val
return (const(ln2)*xp) + val





Not sure this[^] is legal, but it led me to this[^] which seems interesting. The former link is also mentioned in the latter. So it might be.
"I know which side I want to win regardless of how many wrongs they have to commit to achieve it."  Stan Shannon
Web  Blog  RSS  Math  LinkedIn





Good find.
It always takes me an age to translate something from the book into CS, this is a real time saver!





Message Closed
modified 10Mar16 3:41am.





The former link is also mentioned in the latter. So it might be.
LOL.. Got me to 'CLICK'





Message Closed
modified 10Mar16 3:41am.





Message Closed
modified 10Mar16 3:41am.






Yes your test passed.
As of how to accomplish that have you ever tried Google?
Failing that try .



