Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,925 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,924 people online right now. Registration is fast and FREE... Join Now!




Primitive Roots in C

 
Reply to this topicStart new topic

Primitive Roots in C, Calculation

Sacky
6 Jan, 2008 - 08:52 PM
Post #1

New D.I.C Head
*

Joined: 28 Dec, 2007
Posts: 26

So I'm trying to make a function that will calculate a Primitive Root in C, and this is it:

CODE
int PrimitiveRoot(int iPrime)
{
    // Calculate Congugates
    bool* bCongugates = (bool*) malloc(iPrime*sizeof(bool));
    for(int i=0;i<iPrime;i++) bCongugates[i] = true;
    for(int i=2;i<iPrime/2;i++)
        if(!(iPrime % i))
            for(int j=0;j<iPrime;j++)
                if(!(j % i))
                    bCongugates[j] = false;
    // Calculate Primitive Roots
    bool* bPrimitiveRoots = (bool*) malloc(iPrime*sizeof(bool));
    for(int i=0;i<iPrime;i++) bPrimitiveRoots[i] = false;
    for(int i=2;i<iPrime;i++)
    {
        bool* bCongugateTest = (bool*) malloc(iPrime*sizeof(bool));
        for(int j=0;j<iPrime;j++) bCongugateTest[j] = false;
        for(int j=2;j<iPrime;j++)
            bCongugateTest[i^j%iPrime] = true;
        bool bRoot = true;
        for(int j=2;j<iPrime;j++)
            if(bCongugateTest[j] != bCongugates[j])
            {
                bRoot = false;
                break;
            }
        if(bRoot) bPrimitiveRoots[i] = true;
        free(bCongugateTest);
    }
    // Pick a Root
    int iRootCnt = 0;
    for(int i=2;i<iPrime;i++)
        if(bPrimitiveRoots[i] == true)
            iRootCnt++;
    int* iPrimitiveRoots = (int*) malloc(iRootCnt*sizeof(int));
    iRootCnt = 0;
    for(int i=2;i<iPrime;i++)
        if(bPrimitiveRoots[i] == true)
        {
            iPrimitiveRoots[iRootCnt] = i;
            iRootCnt++;
        }
    int iPrimitiveRoot = iPrimitiveRoots[rand() % (iRootCnt+1)];
    // Cleanup and Return
    free(bCongugates);
    free(bPrimitiveRoots);
    free(iPrimitiveRoots);
    return iPrimitiveRoot;
}


Except it randomly crashes throughout the code sad.gif, can anybody see why?
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Primitive Roots In C
6 Jan, 2008 - 09:56 PM
Post #2

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
Do you have a driver program that demonstrates such a crash? It would be nice to see some values that are giving you problems, and probably make the troubleshooting a little easier.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 02:56PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month