473,651 Members | 2,994 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Automatic memoization!!

Has anyone experienced automatic memoization by any C++ compiler
before?

The program coded as a solution for the problem based on the famous 3n
+1 problem, both of which are given below, is automatically memoized.
Is it due to caching of return values or something else? The point is,
does this program exhibit some property which leads to automatic
memoization by the compiler? Which can be satisfied by other programs
too to make them automatically optimized by the compiler?

Also, though this might be considered compiler specific, i have tried
this on microsoft vc++ compiler as well as bloodshed devc++ compiler.
Even without optimization in both of these compilers, this happens.

Problem ( http://projecteuler.net/index.php?se...problems&id=14
) :-
----------------
Problem 14
05 April 2002

The following iterative sequence is defined for the set of positive
integers:

n n/2 (n is even)
n 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following
sequence:
13 40 20 10 5 16 8 4 2 1

It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz
Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one
million.

Answer:
837799
----------------

The solutions given below takes the number below which the longest
chain is to be found as input.

Recursive solution ( http://pastecode.org/2035 ) :-
----------------
#include <stdio.h>

unsigned maxn = 0, maxx = 1;

unsigned solve(unsigned x) {
if(x == 1) return 1;
else return x & 1 ? solve(3 * x + 1 >1) + 2 : solve(x >1) + 1;
}

int main() {
unsigned i, t, n;
scanf("%u", &n);
for(i = 2; i < n; i++)
if(maxn < (t = solve(i))) maxn = t, maxx = i;
printf("%u\n", maxx);
return 0;
}
----------------

There might be a mistake here though. Like i tried incrementing a
global variable (initialized to 0) inside the function to check how
many times control goes inside the function and printed the value in
main after calling the function and it gave the actual number of times
it went in and did not take any extra time and was as fast as it was
without it!

The following code is the non-optimized program since it uses a loop
which essentially does the same thing as the recursion but cannot have
automatic memoization done by the compiler.

Non-recursive solution ( http://pastecode.org/2036 ) :-
----------------
#include <stdio.h>

int main() {
int i, j, l, maxl = 0, maxi = 0, n;
scanf("%d", &n);
for(i = 1; i < n; i++) {
for(l = 1, j = i; j - 1; l++)
j = j & 1 ? 3 * j + 1 : j >1;
if(maxl < l) maxl = l, maxi = i;
}
printf("%d\n", maxi);
return 0;
}
----------------

Thank You
trss
Jul 28 '08 #1
5 2787
Please don't quote signatures.

alright
I've looketh and yes they now seem to be equivalent, just an optimization in the
recursive version.
yeah thnx. but the question is, how does that optimization occur for
this particular recursion alone and not for any other even simple
recursions like factorial calculations and stuff? the depth is also
quite large in this case since chains happen to be quite long for many
values within 1,000,000 which is the actual question in that problem
even for which this recursion gets optimized.

my point is, we could use this technique to code in this "style"
instead of implementing our own hash map and stuff to manually code
memoization. though implementing ourselves isn't much of a big task
when we know the input values to be within a small domain where we can
simply use an array of that size as the cache, it may become slower
(and a bit to code too) if we are to use hash maps and stuff as is the
case with this problem in case memoization wasn't achieved
automatically.
Jul 28 '08 #2
trss <tr****@gmail.c omwrites:
>Please don't quote signatures.

alright
But you should retain attribution lines (the "so-and-so wrote:" bits).
>I've looketh and yes they now seem to be equivalent, just an
optimization in the recursive version.

yeah thnx. but the question is, how does that optimization occur for
this particular recursion alone
Alf Steinbach is probably referring to *your* optimisation. You made
the recursive version do two iterations in one go in the "odd" case.
The two versions are not equivalent, however.

The compiler is not doing any memoization. Are you, perhaps, being
confused by the very long run time of your second (non-recursive)
version? This is caused by the second version not terminating (at
least on my system). Try running it with input 113383 and then with
input 113384.

--
Ben.
Jul 28 '08 #3
On 28 Lug, 14:00, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
The compiler is not doing any memoization. *Are you, perhaps, being
confused by the very long run time of your second (non-recursive)
version? *This is caused by the second version not terminating (at
least on my system). *Try running it with input 113383 and then with
input 113384.
Possibly OT: indeed, it seems that the second algorithm overflows when
i == 113383. Using 32-bit int, the 'j' variable in the inner loop
becomes negative, and the program never terminates.

Dario
Jul 28 '08 #4
On Jul 28, 5:00*pm, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
trss <trs...@gmail.c omwrites:
Please don't quote signatures.
alright

But you should retain attribution lines (the "so-and-so wrote:" bits).
okay!
I've looketh and yes they now seem to be equivalent, just an
optimization in the recursive version.
yeah thnx. but the question is, how does that optimization occur for
this particular recursion alone

Alf Steinbach is probably referring to *your* optimisation. *You made
the recursive version do two iterations in one go in the "odd" case.
The two versions are not equivalent, however.
yes but not coz of the minor optimization. i forgot to add it to the
non-recursive solution. it doesnt give that much of a difference in
execution times. thnx for pointing out though.
The compiler is not doing any memoization. *Are you, perhaps, being
confused by the very long run time of your second (non-recursive)
version? *This is caused by the second version not terminating (at
least on my system). *Try running it with input 113383 and then with
input 113384.
oh man. really sorry. thnx for finding that! i just replaced int with
unsigned in the non-recursive solution guessing that should be the
problem causing this and it worked!! faster than the recursion
ofcourse! :)

so yes there is no automatic memoization by the compiler and hence
something like http://apl.jhu.edu/~paulmac/c++-memoization.html must
only be used (though i haven't tried it out yet).

p.s. - for problem 15 in http://projecteuler.net the problem can be
solved by implementing simple memoization only and it led me to feel
the power of memoization!

thnx ppl
thnx
Jul 28 '08 #5
On Jul 28, 8:03*pm, Dario Saccavino <kath...@gmail. comwrote:
On 28 Lug, 14:00, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
The compiler is not doing any memoization. *Are you, perhaps, being
confused by the very long run time of your second (non-recursive)
version? *This is caused by the second version not terminating (at
least on my system). *Try running it with input 113383 and then with
input 113384.

Possibly OT: indeed, it seems that the second algorithm overflows when
i == 113383. Using 32-bit int, the 'j' variable in the inner loop
becomes negative, and the program never terminates.

* *Dario
right. in fact i checked it with long long unsigned and length of
chains seem different for some inputs though the final answer turns
out to be same as with unsigned.

i actually implemented memoization myself and found running time to
increase in the memoized version which was the actual source of
confusion. implementing memoization for the right code with long long
sure increases performance.

anyway, all confusions apart, the problem is only with overflow and no
automatic memoization is done by usual compilers.

thnx
Jul 29 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2439
by: Rasmus Fogh | last post by:
Someone raised the question of automatic code generation a few weeks back. And yes, we (CCPN) are using automatic Python code generation in a major way. Basically we are making data models in UML, and using automatic code generation to make Python APIs, XML I/O etc. (more below). We can be found at http://www.ccpn.ac.uk/index.html As a general point, automtic code generation would seem like a good idea in special cases where:
0
1376
by: Mark E. Fenner | last post by:
In the code below, the class DifferentCache utilizes three different memoization (caching) strategies. Neither the function Memoize1 or the class Memoize2 will be adequate for all three of these cases (I intend these to be used as, for example, getInstanceValueFunction = Memoize1(getInstanceValueFunction) within the DifferentCache class definition). Memoize1 will have problems with getMemberValueFunction b/c it will try to generate a...
6
5471
by: Gert van der Kooij | last post by:
Hi, It's no problem to define the automatic maintenance using the wizard but I want to use commands to automate automation. I captured the SQL statements when activating the maintenance but that didn't help. I couldn't find anything about it in the docs so if anybody could help with this it would be great. Kind regards, Gert
13
1421
by: Steven D'Aprano | last post by:
I was playing around with simple memoization and came up with something like this: _cache = {} def func(x): global _cache if _cache.has_key(x): return _cache else: result = x+1 # or a time consuming calculation...
1
4036
by: Michel Esber | last post by:
Hello, Linux RedHat AS4 running DB2 V8 FP11. I have followed the docs at http://tinyurl.com/qckrn and enabled automatic statistics collection. It has been 2 days since I updated my DB cfg and I don´t see any activity regarding auto runstats. Also, the field STATS_TIME from syscat.tables shows that all my table statistics were last collected in March. What am I missing here ? Is
58
4643
by: Jorge Peixoto de Morais Neto | last post by:
I was reading the code of FFmpeg and it seems that they use malloc just too much. The problems and dangers of malloc are widely known. Malloc also has some overhead (although I don't know what is the overhead of automatic variable sized arrays, I suspect it is smaller than that of malloc), although I'm not too worried about it. I was thinking that, with C99's variable length arrays, malloc shouldn't be needed most of the time. But I'm...
3
4642
by: myjish18 | last post by:
Hello, We have a DB2 UDB database v8.2.7 (db2 v8.2 fixpak 14) on AIX 5.3 which has Automatic Storage (AS) enabled. We want to disable automatic storage on entire database and/or disable automatic storage on all tablespaces. DB2 Manual says it once AS is enabled, it cant be changed. Is there any way to disable the AS or any other alternative? Please advice.
7
1990
by: ssecorp | last post by:
I am not clear about the results here. from timeit import Timer import Decorators def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1
25
2646
by: sidd | last post by:
In the following code: int i = 5; ---it goes to .data segment int j; ---it goes to bss segment int main() { int c; int i = 5; ---stack
0
8361
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8807
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8701
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7299
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5615
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4290
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1588
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.