mod arithmetic in C++

This is a discussion on mod arithmetic in C++ within the C++ Programming forums, part of the General Programming Boards category; hi, i have been trying to get some mod arithmetic done in C++ but i am having some problems. It ...

  1. #1
    Unregistered
    Guest

    Question mod arithmetic in C++

    hi,

    i have been trying to get some mod arithmetic done in C++ but i am having some problems. It gives me a different asnwer ( the wrong one)...i believe its the size of the var. but i could be wrong.


    result = powl(m,e);
    c = fmodl(result,n);
    results = powl(c,d);
    mm = fmodl(results,n);

    for c, getting the result of 3^13 mod 77 is not a problem (its 38). But for mm, which is BTW 38^37 mod 77, i get 0 or 8 instead of 3 (3 is the right answer).

    FYI: results, result and mm are long double; while c,d,e and n are integers.
    ideas anyone?

  2. #2
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    For integer modulus use the % operator or for powers of 2 use the & operator with (n-1).

    So for 5000 mod 4096 you could do:

    int num=5000%4096;

    or

    int num=5000 & 0x0FFF;

    The & operation is quicker but only works on powers of 2.

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    Are you sure the correct answer is 3? What did you use to calculate (38^37) % 77?
    Here is some code and answers I got.
    Code:
    int main()
    { 
    	double dn1 = 38, dn2 = 37, dmod = 77 , dresult,dtemp;
    	long double ldn1 = 38, ldn2 = 37, ldmod = 77, ldresult,ldtemp;
    		
    	cout << "Using doubles " << endl;
    		
    	dtemp = powl(dn1,dn2);
    	dresult = fmodl(dtemp,dmod);
    
    	cout << dresult << endl;
    
    	cout << "Using long doubles " << endl;
    	
    	ldtemp = powl(ldn1,ldn2);
    	ldresult = fmodl(ldtemp,ldmod);
    
    	cout << ldresult << endl;
    
    	return 0;
    }
    And here is the output i got
    Using doubles
    30
    Using long doubles
    8

    so there is a problem here. Either the doubles are over flowing, or using long doubles results in wrong answers.
    Using limits.h and DBL_MAX on my system doubles max out at 1.79769e+308. So i think its just an error due to trying to use long doubles.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21