Vous êtes sur la page 1sur 41

[x]

Ever Worried about Missed / Lost Mobile Phone (or) Mobile Phone Theft ?
Use GinGly to Save your Mobile Numbers and Useful Messages
Limited Time Free Access .Hurry Up !!!

Login

Top of Form

Forever Login

Login with username, password and session length

Bottom of Form
Resend Activation Email | Forgot your Password?
Join IT Acumens Discussion Zone Free!
Welcome, Guest. Please login or register.
Top of Form

Login

Bottom of Form
September 16, 2010, 05:35:00 PM
Top of Form
Search... 16101

Bottom of Form

• Home

• Search

• Team

• Calendar

• Gallery

• Contact

• Downloads

• GoogleTagged

• Login

• Register

• IT Acumens Discussion Zone »

• Tech News »
• Programming Discussions for Engineers »

• Programming Stuffs in "C" (Moderators: VelMurugan, thiruvasagamani) »

• Find the greatest common divisor of 2 numbers a and b and also find 2 numbers x

« previous next »

• Reply

• Print

• Register to comment on this topic

Pages: [1]

Author Topic: Find the greatest common divisor of 2

numbers a and b and also find 2 numbers x (Read 3054 times)


Top of Form

sams.raghu

• dont know where to stay now

• Senior Acumen

• Hero Member

• Posts: 509

Find the greatest common divisor of 2 numbers a and b and also find 2 numbers x
« on: July 14, 2008, 07:29:59 PM »

• Quote
Find the greatest common divisor of 2 numbers a and b and also find 2 numbers x and y
such that ax + by = GCD(a,b)

Sol:

Every number is divisible by 1, and so the least common divisor of a pair of numbers is 1. The more
challenging problem is to find the Greatest Common Divisor (GCD), the largest divisor common to a
set of given integers.

The naive way of finding the GCD is to find all divisors of one number and test each of these for
divisibility on the second. Another way would be to find the prime factorization of both numbers
and find product of all common factors. But, as you can see, these methods are more brute-force
and will be computationally intensive.

Euclid’s algorithm for GCD computation was one of the earliest interesting algorithms in history. It
is based of a couple of basic observations.

1. If b divides a, then GCD(a,b) equals b

2. If a = bn + k, then GCD(a,b) = GCD(b,k)

The first observation is pretty straight forward. If b divides a, then a = bn where n = 1,2,3.. and so
GCD(a,b) = GCD(bn,b) = b

For the second observation, GCD(a,b) = GCD(bn+k, b) Any common divisor of a and b is now
dependant on k, since bn is divisible by b.

From this you see that the algorithm is recursive. Replace the bigger integer by its remainder mod
smaller integer. This basically cuts down the integer size to at least half for each step, and thus the
running time of the algorithm is logarithmic number of iterations to the naive ones discussed
above.

An outcome of Euclid’s algorithm is that you can find more than just the GCD(a,b). In fact you can
also find two integers x and y such that

ax + by = GCD(a,b)

Code: [Select]
int GCD(int a, int b,
int& x, int& y)
{
int prevX, prevY;
int
gcd;

if(b > a)
{
return GCD(b,a,y,x);

if(b == 0)
{
x=1;

y=0;
return a;
}

gcd = GCD(b, a%b, prevX,


prevY);
x = prevY;
y = prevX - FLOOR(q/b) * prevY;

return gcd;
}

Logged

Share your Interesting Things Here[url]

Bottom of Form

• Reply

• Print
• Register to comment on this topic

Pages: [1]
« previous next »

• IT Acumens Discussion Zone »

• Tech News »

• Programming Discussions for Engineers »

• Programming Stuffs in "C" (Moderators: VelMurugan, thiruvasagamani) »

• Find the greatest common divisor of 2 numbers a and b and also find 2 numbers x

GoogleTagged
naive then program find gcd numbers divisior comman compute program force two

programme gcd caluclate findimg brute integer for recursive the

===> Programming Stuffs in "C"

Jump to:

Related Topics
Subject / Started by Replies Last post

Linux By The (Version) Numbers March 26, 2008,


0 Replies
Started by hari Windows / Linux 224 Views 07:37:30 PM
by hari

Find the Smallest of ten Numbers July 28, 2008,


0 Replies
Started by karthikn Programming Skills in "C++" 267 Views 08:15:13 PM
by karthikn

Program to find the average of N Numbers July 28, 2008,


0 Replies
Started by karthikn Programming Skills in "C++" 1605 Views 08:18:32 PM
by karthikn
Program tofind the smallest numbers and biggest
0 Replies August 07, 2008,
numbers
571 Views 08:11:10 PM
Started by thiruvasagamani Programming Stuffs in "C"
by thiruvasagamani

Program to find G.C.D and L.C.M of two numbers September 22,


0 Replies
Started by thiruvasagamani Programming Stuffs in "C" 6494 Views 2008, 12:18:29 PM
by thiruvasagamani
Top of Form

Bottom of Form

Top of Form

Bottom of Form

ITAcumens © 2006-2010. All Rights Reserved


Sitemap | About Us | Advertise |
Internet Rank | Contact Us | XHTML |
RSS | WAP2

Powered by SMF 2.0 RC2 | SMF © 2006–2009, Simple Machines LLC


Theme by DzinerStudio
Page created in 0.718 seconds with 44 queries.

Read more: http://discuss.itacumens.com/index.php?topic=16101.0#ixzz0zh4Kcs8b

C programming questions and answer

C ,C++, Advance C Search Engine

Top of Form
partner-pub-0153 ISO-8859-1 Search

cquestionbank.blo cquestionbank.blo cquestionbank.blo

Bottom of Form

Java, Reasoning, Aptitude, Ebooks Search Engine

Top of Form

partner-pub-0153 ISO-8859-1 Search

Bottom of Form

find g.c.d of two number using c program

#include<stdio.h>

int main(){

int n1,n2;

printf("\nEnter two numbers:");

scanf("%d %d",&n1,&n2);

while(n1!=n2){

if(n1>=n2-1)

n1=n1-n2;

else

n2=n2-n1;

printf("\nGCD=%d",n1);

return 0;

}
Logic of HCF or GCD of any two numbers:

In HCF we try to find any largest number which can


divide both the number.

For example: HCF or GCD of 20 and 30

Both number 20 and 30 are divisible by 1, 2,5,10.

HCF=max (1, 2, 3, 4, 10) =10

Logic for writing program:

It is clear that any number is not divisible by more


than that number. In case of more than one number s,
a possible maximum number which can divide all of the
number s must be minimum of all of that numbers.

For example: 10, 20, and 30

Min (10, 20, 30) =10 can divide all there numbers. So
we will take one for loop which will start form min
of the numbers and will stop the loop when it became
one, since all numbers are divisible by one. Inside
for loop we will write one if conditions which will
check divisibility of both the numbers.

Program:

#include<stdio.h>

int main(){

int x,y,m,i;

printf("Insert any two number: ");


scanf("%d%d",&x,&y);

m=x

for(i=m;i>=1;i--){

if(x%i==0&&y%i==0){

printf("\nHCF of two number is : %d",i) ;

break;

return 0;

4 comments:

Anonymous said...

im finding solution for this programme since 5days.now i got the logic but better to
explain the programme in theriotically please.its reaaly need for basic learner like me.

regard
geeta

8/31/09 6:17 PM

Anonymous said...

please explai me the some more clearly

6/18/10 6:31 PM
Anonymous said...

please explain logic clearly.....i cant understand

6/18/10 6:33 PM

Gan said...

Good answers. But i found a bit mistake in the second code. Please correct it other
wise novice can get trouble.

Regards
Ganesh Slv

9/2/10 4:48 PM

Post a Comment

Links to this post


Create a Link

Newer Post Older Post Home


Subscribe to: Post Comments (Atom)

C Questions & Explanation


Big index of c questions
C program examples
Data type questions
Variable naming rule questions
Operators questions
Control flow questions
Switch case questions
Looping questions
Pointer questions
More pointer questions
Array questions
String questions
Function questions
Printf,Scanf questions
Preprocessor questions
Structure questions
Union questions
File handling questions
Commad line argument
C questions in Linux
C interview questions
C online test
C mixed practice sets
C tricky questions
Good c questions
C example code
c examples with code

C Interview Questions & Answer


C interview questions
Data type inteview questions
Storage class interview questions
String interview questions
Pointer interview questions

C Language Tutorials
Memory map tutorial
Data type tutorial
Variable tutorial
Storage class tutorial
Operator tutorial
Control flow tutorial
Looping tutorial
Array tutorial
String tutorial
Pointer tutorial
Function tutorial
Preprocessor tutorial
Structure tutorial
Union tutorial
File handling tutorial
Command line argument in c
Advance c tutorial

Other Topics

Preparation of placement for fresher


Java questions with solution
Sql questions with solution
Advance java tutorial
Download free ebooks
Download PC softwares

Share this tutorial at

Subscribe To
Posts

Atom

Posts

Comments

Atom

Comments

Standard of questions ?

C Questions and Explanation


Top of Form

partner-pub-0153 ISO-8859-1 Search


Bottom of Form

Pages
• Home

C lover community

Copyright@ritesh kumar. Picture Window template by Josh


Peterson. Powered by Blogger.

/*

Written by Sanchit Karve A.K.A born2c0de

born2c0de AT hotmail DOT com

*/

#include <stdio>

int euclid(int a,int b)

if(b==0)
return a;

else

return euclid(b,a%b);

int main()

int n1,n2;

printf("Enter two numbers to find its GCD:");

scanf("%d %d",&n1,&n2);

printf("The GCD of %d and %d is %d",n1,n2,euclid(n1,n2));

return 0;

GCD Algorithm
If two numbers are divisible by x, then so is their sum and diffference. Call the first number
x×y and the second x×z, and invoke the distributive property. The sum is x×(y+z) and the
difference is x×(y-z). Both are obviously divisible by x. This simple fact can be used again
and again to quickly home in on x. Let's look at a simple example.

What number x divides both 100 and 36? It must also divide 100-36. In fact it
divides 100-36-36, which is the remainder of 100÷36. This remainder, 28, is
necessarily smaller than 36 - we've made progress. But what divides evenly into 36
and 28? Subtract again to get 8. Then divide 28 by 8, giving a remainder of 4.
Finally 8 and 4 produce a remainder of 0, terminating the algorithm. Now 4 divides
both 100 and 36, and if any other number, such as 2, also divides 100 and 36, it
must divide evenly into 4. After all, 2 is subject to the same procedure, dividing
evenly into all the differences and remainders, all the way down to 4.
The above procedure, called Euclid's gcd algorithm, extracts the greatest common
divisor x, because any other common divisor y divides evenly into each difference
and remainder along the way, until finally, y divides x. The result, x, is truly a
"greatest common divisor", since it contains every other common divisor y.
If x is 1, the two numbers are "relatively prime", or "coprime". They have no factors
in common.
The word incommensurable originally meant "no common divisors", and it can still be
used this way, though it is more often used to describe items or ideas that cannot be
reasonably compared, as in incommensurable theories.
If g is the gcd of s and t, what is the gcd of cs and ct? Certainly cg (c×g) divides both
cs and ct. If the greatest common divisor is actually larger, let cgk divide cs and ct,
where k takes up the slack. Divide through by c, and gk divides both s and t. This is
a contradiction, since g is already the gcd of s and t. Thus cg is the gcd of cs and
ct. This can be summarized by saying, multiplication distributes over gcd. Multiply
two numbers by c, and that multiplies their gcd by c.
Note that the gcd algorithm is efficient, even for large numbers. The remainder
(rounding up or down) is at most half the divisor, so it doesn't take long to reach the
gcd. Each step introduces another bit of precision. In fact, the algorithm is at least
28% faster than this simple calculation would suggest, but you need the theory of
continued fractions to prove this. In any case, the algorithm is efficient. We may not
be able to factor two huge numbers, but we can quickly tell if they have any factors in
common.
Most modern factoring methods employ the gcd algorithm inside, a real tribute to
Euclid. If n = p×q, a factoring program such as the elliptic curve method generates
values of k in clever ways, hoping to stumble upon something divisible by p or q. But
we don't know what p and q are ahead of time, so how do we measure success?
Answer: run the gcd algorithm on k and n. If k is divisible by p, gcd(k,n) will produce
p in short order. Of course, you can spend your entire career looking for clever ways
to generate k, so that it is more likely to have a factor in common with n. Obviously,
choosing k at random won't get you very far.
Snippet

1. /*
2. Written by Sanchit Karve A.K.A born2c0de
3. born2c0de AT hotmail DOT com
4. */
5. #include <stdio>
6.

7. int euclid(int a,int b)


8. {

9. if(b==0)

10. return a;

11. else

12. return euclid(b,a%b);


13. }
14.

15. int main()


16. {

17. int n1,n2;

18. printf("Enter two numbers to find its GCD:");

19. scanf("%d %d",&n1,&n2);

20. printf("The GCD of %d and %d is %d",n1,n2,euclid(n1,n2));

21. return 0;
22. }
23.
24.
The Greatest Common divisor
by NEMO_1990_2007 on Oct 16th, 2008

The greatest common divisor of integers x and y is the largest integer that evenly divides both x
and y. Write a recursive method Gcd that returns the greatest common divisor of x and y. The
Gcd of x and y is defined recursively as follows: If y is equal to 0, then Gcd( x, y ) is x; otherwise,
Gcd( x, y ) is Gcd( y, x % y ), where % is the modulus operator.

Could you help me with it (I feel it is very wrong).

C Code Snippet (Toggle Plain Text)

1. using System;
2. using System.Collections.Generic;
3. using System.Text;
4.
5. namespace exe_2_4
6. {
7. class Program
8. {
9. static void Main(string[] args)
10. {
11. int x, y;
12. Console.WriteLine("enter the value of x");
13. x = int.Parse(Console.ReadLine());
14. Console.WriteLine("enter the value of y");
15. y = int.Parse(Console.ReadLine());
16. gcd(x, y);
17. }
18. public static void gcd(int x, int y)
19. {
20. int z= x%y;
21. if (y == 0)
22. Console.WriteLine("the GCD({0},{1}) is {0}", x, y);
23. else
24. Console.WriteLine("the GCD({0},{1}) is ({1}, {2})", x,y, z);
25. }
26. }
27. }
using System;
using System.Collections.Gener
using System.Text;

namespace exe_2_4

Comments on this Code Snippet

Manipal Part Time MBA


Designed for working professionals. Classes on weekends. Apply Now !
Manipal.edu/AdmissionsOpen2010

Ads by Google

Permalink

Oct 18th, 2008

Re: The Greatest Common divisor


Try this:

C Syntax (Toggle Plain Text)


1. public static int gcd(int x, int y)
2. {
3. //First quote from the question:
4. //"If y is equal to 0, then Gcd( x, y ) is x; "
5.
6. if (y == 0) return x;
7.
8. //Second quote:
9. //"otherwise, Gcd( x, y ) is Gcd( y, x % y ), where % is the
modulus operator"
10.
11. else return gcd(y, x % y);
12.
13. //so it's seems that you just had to translate your question
into code!!!
14. //but I have to admit, recursion is hard to grasp at first.
15. }
public static int gcd(int x, int y)
{
//First quote from the qu
//"If y is equal to 0, then

Perhaps you should try the original divised by the greek Euclid :

C Syntax (Toggle Plain Text)


1. public static int gcd2(int x, int y)
2. {
3. while (x != y)
4. {
5. if (x > y)
6. {
7. x = x - y;
8. }
9. else
10. {
11. y = y - x;
12. }
13. }
14. return x;
15. }
public static int gcd2(int x, int y)
{
w hile (x != y)
{
if (x > y)

Remember the modulus operator is really a substraction operator!


have fun!

Recursion
Program #1: Factorial
This computes a factorial recursively.
#include <stdio.h>

/*
* compute n! recursively
*/
int fact(int n)
{
/* error check */
if (n < 0)
return(-1);
/* base case */
if (n == 0)
return(1);
/* recursion */
return(n * fact(n-1));
}

/*
* convert string to int with error checking
* no leading signs or magnitude checking
*/
int cvttoint(char *s)
{
int n = 0; /* integer being read */

/* skip leading white space */


while(isspace(*s))
s++;
/* if it's not a digit, it's not an integer */
if (!isdigit(*s))
return(-1);
/* read in the integer */
while(isdigit(*s))
n = n * 10 + *s++ - '0';
/* if it's ended by a NUL, it's an integer */
return(*s ? -1 : n);
}

int main(int argc, char *argv[])


{
int i; /* counter in a for loop */
int n; /* number read in */
int rv = 0; /* exit status code */

/*
* do each arg separately
*/
for(i = 1; i < argc; i++)
if ((n = cvttoint(argv[i])) != -1)
printf("%d! = %d\n", n, fact(n));
else{
/* error handler*/
rv++;
printf("%s: invalid number\n", argv[i]);
}

/*
* bye!
*/
return(rv);
}
Program #2. Greatest Common Divisor
This computes the GCD recursively.
/*
* gcd -- compute the GCD of pairs of integers
*
* History
* 1.0 Matt Bishop; original program
* 1.1 Matt Bishop; made it recursive
*/
#include <stdio.h>

/*
* macros
*/
#define BAD_GCD -1 /* error in arguments -- */
/* MUST be non-positive */

/*
* recursive GCD
*/
int gcdr(int m, int n)
{
/* base case(s) */
if (m == 0)
return(n);
if (n == 0)
return(m);
/* now recurse */
return(gcd(n, m % n));
}

/*
* This function returns the greatest common divisor of its arguments
* Notes: (1) if m = n = 0, the GCD is undefined -- so we return BAD_GCD
* (2) if m < 0 or n < 0, then gcd(m,n) > 0; so we can just make
* m and n both positive
* (3) if m = 0 and n != 0, gcd(m,n) = n (and vice versa)
*/
int gcd(int m, int n)
{
int rem; /* remainder for Euclid's
algorithm */

/*
* special cases
*/
/* error check -- if both 0, undefined */
if (m == 0 && n == 0)
return(BAD_GCD);
/* make all negatives positive */
if (m < 0) m = -m;
if (n < 0) n = -n;

/*
* now apply the recursive algorithm
*/
return(gcdr(m, n));
}

/*
* the main routine
*/
void main(void)
{
int m, n; /* numbers to take the GCD of
*/
int g; /* the GCD of m and n */
int c; /* used to gobble up rest of line */

/*
* loop, asking for numbers and printing the GCD
*/
while(printf("Enter two numbers: "),
scanf("%d %d", &m,
&n) != EOF){
while((c = getchar()) != EOF && c != '\n')
;
/* print the result -- note that if the input */
/* is invalid, gcd() simply returns BAD_GCD */
printf("The GCD of %d and %d is ", m, n);
if ((g = gcd(m, n)) == BAD_GCD)
printf("undefined.\n");
else
printf("%d.\n", g);
}

/*
* clean up output and exit
*/
putchar('\n');
exit(0);
}
Program #3. Sorting
This is a very simple recursive sorting program.
#include <stdio.h>

/*
* the array and its size
*/
int list[] = { 13, 82, 0, 16, 5, -1, 99, 0 };
int nlist = sizeof(list)/sizeof(int);

/*
* recursive sort -- put smallest element at head of array
* and then sort the rest
*/
void sort(int l[], int lsz)
{
int i; /* counter in a for loop */
int tmp; /* used to swap ints */
int min; /* index of minimum element */

/* base case */
if (lsz == 1)
return;

/* find index of smallest number in array */


min = 0;
for(i = 1; i < lsz; i++)
if (l[i] < l[min])
min = i;

/* move smallest element to 0-th element */


tmp = l[0];
l[0] = l[min];
l[min] = tmp;

/* recurse */
sort(&l[1], lsz-1);
}

int main(void)
{
int i; /* counter in a for loop */

/* print initial array */


printf("initial array: ");
for(i = 0; i < nlist;i++)
printf(" %3d", list[i]);
putchar('\n');

/* now sort */
sort(list, nlist);

/* print sorted array */


printf("final array: ");
for(i = 0; i < nlist;i++)
printf(" %3d", list[i]);
putchar('\n');
return(0);
}
ECS 30-A, Introduction to Programming
Spring Quarter 2002
Email: cs30a@cs.ucdavis.edu

Factorial recursive

#include<stdio.h>

main()

int a, fact;

printf("\nEnter any number: ");

scanf ("%d", &a);

fact=rec (a);

printf("\nFactorial Value = %d", fact);

rec (int x)

int f;

if (x==1)

return (1);

else

f=x*rec(x-1);

return (f);

}
/* Calculate factorial by using recursion */
#include
#include

int fact(int k)
{
if(k==0)
return 1;
else
return k*fact(k-1);
}

void main()
{
int n;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
printf("\n Factorial value=%d",fact(n));
getch();
}

#include <cstdio> /*or stdio.h depending on platform/compiler*/

/* Fib function, it cannot call itself with f-1 and f-2,

* so we add up to the number given using an iterative sequence


*/

int fib(int n)

int f2=0;

int f1=1;

int fib=0;

int i;

if (n==0 || n==1)

return n;

for(i=2;i<=n;i++){

fib=f1+f2; /*sum*/

f2=f1;

f1=fib;

return fib;

int main()

int fibNum;

int i;

for (i=0; i<=12; i++){

fibNum = fib(i); /*figure out the fib number of the given value ("i")*/

printf("%d\n\n", fibNum);/*print out the i fib number*/

}
return 0;

Top of Form

0 3181 Rate this snippet!

Bottom of Form

Views: 2,843

Language: C

Last Modified: March 12, 2009

Instructions: Implement when you need to solve this type of problem iteratively rather then
recursively.

Snippet

1. #include <cstdio> /*or stdio.h depending on platform/compiler*/


2.
3. /* Fib function, it cannot call itself with f-1 and f-2,
4. * so we add up to the number given using an iterative sequence
5. */

6. int fib(int n)
7. {

8. int f2=0;

9. int f1=1;

10. int fib=0;

11. int i;
12.
13. if (n==0 || n==1)

14. return n;

15. for(i=2;i<=n;i++){

16. fib=f1+f2; /*sum*/


17. f2=f1;
18. f1=fib;

19. }

20. return fib;


21. }
22.

23. int main()


24. {

25. int fibNum;

26. int i;
27.

28. for (i=0; i<=12; i++){

29. fibNum = fib(i); /*figure out the fib number of the given value
("i")*/

30. printf("%d\n\n", fibNum);/*print out the i fib number*/

31. }
32.

33. return 0;
34.
35. }

• >IT Professionals
○ IT Management
○ Security
○ Storage
○ Server
○ Networking
○ Small Business
○ Communications
○ Enterprise Applications
○ Database
○ Mobile
○ Hardware
○ IT News
• >Developers
○ Architect
○ Java / OS
○ Microsoft Technology
○ Web Development
• >Solutions

○ HotList
○ Video
• eBook Library

• Webopedia

• >Login

○ Manage My Profile
• >Register

○ Why Join?

DevX Home Today's Headlines Articles Archive Skill Building Tip Bank Sourcebank

Top DevX Stories

Mule Heads to the Clouds With New Open Source ESB


Release
5 Alternatives to Digg
A New Role for the Business Analyst
Intel Parallel Studio 2011 Optimizes Serial and Parallel
Applications for Multicore and Scales for Manycore
Intel Touts Sandy Bridge Processors, McAfee Plans

Top of Form
process 0

simplesearch

Search the forums:

Bottom of Form
DevX.com Forums Top of Form
> DevX Developer Us e r Na me
User Name
Forums > C++ Remember Me?

Log in
Left To Right Password
Binary
Exponentiation
bdd8eeeaa75421 guest login

Bottom of Form

Register FAQ Members List Calendar Today's Posts Search

Search Forums

Top of Form
process 1 1 1 bdd8eeeaa75421 guest

Go

Show Threads Show Posts

Bottom of Form

Tag Search

Advanced Search

Go to Page...

Top of Form

Bottom of Form
Thread Tools Rate Thread Display Modes

#1

05-05-2009, 03:35 AM

Join Date: May 2007


Peter_APIIT
Posts: 842
Registered User

Left To Right Binary Exponentiation

Hello to all, i try to code the binary exponentiation algorithm but unfortunately it is not
working as desire.

I decided to switch back to You could try using std::numeric_limits<int>::digits to


determine the values and sizes or using CHAR_BIT.

My logic is define at below.

Look at most significant set bit(1) and discard it which follow by scanning from Left to
right

If bit Is 1 then
base * result * result % modulus;
else
result * result % modulus;

My question is how to translate these to code.


Another question is i doubt whether the modulus step need to performed in each loop or
outside the loop.

result = result % modulus at outside of loop or inside of loop at every step.

My current code.

Code:

Code:

ulong LeftRightExponentiation(ulong& base,


ulong& exponent, const ulong& modulus)
{

ulong result(1);

// Reverse exponent
exponent = (((exponent & 0xaaaaaaaa) >> 1) | ((exponent & 0x55555555) << 1));
exponent = (((exponent & 0xcccccccc) >> 2) | ((exponent & 0x33333333)
<< 2));
exponent = (((exponent & 0xf0f0f0f0) >> 4) | ((exponent & 0x0f0f0f0f) <<
4));
exponent = (((exponent & 0xff00ff00) >> 8) | ((exponent & 0x00ff00ff) <<
8));
exponent = ((exponent >> 16) | (exponent << 16));

while (exponent)
{
// Check Least Significant Bit after reverse
if ((exponent & 1) == 1)
{
// Square and Multiply Base
result = base * (result * result);
}
else
{
// Square only
result = result * result ;
}
exponent >>= 1;
}

result = result % modulus;

return result;
}
Thanks.

Peter_APIIT

View Public Profile

Find all posts by Peter_APIIT

#2

05-05-2009, 11:14 PM

Join Date: May 2007


Peter_APIIT
Posts: 842
Registered User

Since left to right binary exponentiation is faster than right to left but the implementation
is difficult for left to right. Therefore, i need good algorithm.

Thanks.

Peter_APIIT

View Public Profile

Find all posts by Peter_APIIT

#3

05-06-2009, 06:33 AM

Join Date: May 2007


Peter_APIIT
Posts: 842
Registered User

I got a logic like this where set a variable name mask to 1 first. The continue shift from
right to left until it meet the exponent bit is one and its left bits is zero. Then this is the
MSB of exponent.

For instance, exponent is 13 and mask is 16 after shift from above step.

EDIT: This algorithm is not working unless there are another algorithm that can extract
most significant set bit then shift right once.

Do anyone have an algorithm to extract most significant set bit ?

Quote:
0001 0000 Mask
0000 1101 Exponent

Then, shift 2 location to right become 0000 0100 which is 4. Meanwhile, i have discard
the 2 ^ 3 of exponent which MSB.

Now need to test the bit for exponent.


If mask & exponent is 1 then square and multiple result else is square and continue shift
the mask to right.

Does this sound working ?

Thanks.

EDIT:

I think this will not working for bigNum. What is your opinion ?

I got code from another forum but i don't understand the logic.

Code:

while(exponent)
{
result *= result;

if (exponent & 0x80000000)


result *= base;
result %= modulus;

exponent <<=1;
Thanks for your explanation.

Please suggest better approach that scale and efficient.

Thanks.

Last edited by Peter_APIIT; 05-06-2009 at 07:59 AM. Reason: Add some information

Peter_APIIT

View Public Profile

Find all posts by Peter_APIIT

#4

05-07-2009, 01:52 PM

Join Date: Dec 2007


vijayan
Posts: 333
Registered User

pingala's algorithm is an exceptionally simple one.


http://primes.utm.edu/glossary/xpage...entiation.html

Code:
#include <string>
#include <iostream>
#include <bitset>
#include <limits>
#include "BigIntegerLibrary.hh"

BigUnsigned chanda_sutra_exp( BigUnsigned base, unsigned long exponent )


{
using std::string ;
using std::bitset ;
typedef std::string::size_type size_type ;

enum { NBITS = std::numeric_limits<unsigned long>::digits } ;


string bits = bitset< NBITS >( exponent ).to_string() ;
size_type first_one_bit = bits.find('1') ;

if( first_one_bit == std::string::npos ) return 1 ;

BigUnsigned number = base ;


for( size_type i = first_one_bit+1 ; i < NBITS ; ++i )
{
number *= number ;
if( bits[i] == '1' ) number *= base ;
}
return number ;
}

int main()
{
BigUnsigned b( stringToBigUnsigned("12345678901234") ) ;
unsigned long e = 123U ;
std::cout << b << " ^ " << e << " == " << chanda_sutra_exp( b, e ) << '\n' ;
}
Quote:

12345678901234 ^ 123 ==
1804438967039618200459335773619173442740105594221884421352010220593811
16783781522469671961
3293640383299696815732854191716388109541280643845523172129056391341749
36093920948035266222
1504206004064887386898387848731138992348511188150429918314587833174841
76052073131570932075
7428444592661565299355855018345266510485847260881639957969611091250157
70165270115568281349
0760529437386409237227690149648535626874927135311576766657019881856016
39312013333796300474
6529444102679484450292662643657669295248021580791559217487842913197707
48841023264005406753
2287891233886171879835374480878389763049743620670516444301571022136589
84647690954869874567
2303811751552954552453459883236087293303181921020998977777702578650877
99616704693619702131
9994523389492977668655365754700211842690057768848450037650859536338460
21763517794228156761
9874566990240713276419035254405223528059446013030152169454305800909061
26424960372696235237
5850109676749897175392761911015973214320677261809052959460065483432489
38008541604628707674
1744528689891126276797966747587046017874740773960827122687028455656147
02181244933388881255
4943662875988524396330906170327053173265611559822760604277549634786815
35044418447171563269
8617561475875713072316682528964778669390098375525948112356859970756755
07189619192328432465
2686902755013411964710877557821355760361408433120398326930099326564050
72705345490134573201
2726038232741092528911654950541392514146558567760867889679552159751116
62710966671022511729
6500040028464914396087002390331860222126019738457709529579638956401682
92959156600555981700
5636535639565539486978916017821592691107297272948285736125659535328926
31325999104

vijayan

View Public Profile

Find all posts by vijayan

#5

05-08-2009, 03:40 AM

Join Date: May 2007


Peter_APIIT
Posts: 842
Registered User

I try with your solution but return wrong result.


For instance, base = 4, exponent = 13 and modulus = 497. The result should be 445 but
the program return 30.
Code:
ulong LeftRightExponentiation(ulong& base,
ulong& exponent, const ulong& modulus)
{
// To & each bit with exponent
// ulong mask(1);
ulong result(1);

// integer datatype large enough to


// represent any possible string size
typedef string::size_type strSize;
enum {NBITS = numeric_limits<ulong>::digits };

string bitExponent = bitset<NBITS>((unsigned long)exponent).to_string();


strSize MSSBPos = bitExponent.find('1');

// Default npos is -1 if it is not found


if (MSSBPos != string::npos)
{
// Discard MSSB
MSSBPos += 1;
while (MSSBPos < NBITS)
{
result *= result;

if (bitExponent[MSSBPos] == '1')
{
result = (result * base);
}

result = result % modulus;

++MSSBPos;
}
}

return result;

}
Thanks.

Peter_APIIT

View Public Profile

Find all posts by Peter_APIIT


#6

05-08-2009, 07:31 AM

Join Date: Dec 2007


vijayan
Posts: 333
Registered User

> I try with your solution but return wrong result.

you tried your solution, not mine. and your solution still is as broken as it was in your
first post.

Code:
#include <string>
#include <iostream>
#include <bitset>
#include <limits>
#include "BigIntegerLibrary.hh"

BigUnsigned chanda_sutra_exp_modulo( BigUnsigned base, unsigned long exponent,


BigUnsigned modulus )
{
typedef std::string::size_type size_type ;
enum { NBITS = std::numeric_limits<unsigned long>::digits } ;

std::string bits = std::bitset< NBITS >( exponent ).to_string() ;


size_type first_one_bit = bits.find('1') ;

if( first_one_bit == std::string::npos ) return 1 ;

// ( a * b ) (mod m ) == ( ( a (mod m) ) * ( b (mod m) ) ) (mod m)


BigUnsigned number = base % modulus ;
for( size_type i = first_one_bit+1 ; i < NBITS ; ++i )
{
number = ( number * number ) % modulus ;
if( bits[i] == '1' ) number = ( number * base ) % modulus ;
}
return number ;
}

int main()
{
std::cout << "( 4 ^ 13 ) (mod 497) == "
<< chanda_sutra_exp_modulo( 4, 13, 497 ) << '\n' ;

BigUnsigned b( stringToBigUnsigned("1234567890123456789012345") ) ;
unsigned long e = 1234567U ;
BigUnsigned m( stringToBigUnsigned("98765432109") ) ;
std::cout << "( " << b << " ^ " << e << " ) (mod " << m << ") == "
<< chanda_sutra_exp_modulo( b, e, m ) << '\n' ;
}
Quote:
>g++44 -Wall -std=c++98 -pedantic -Werror -O3 pingala.cc Big*.cc && ./a.out
( 4 ^ 13 ) (mod 497) == 445
( 1234567890123456789012345 ^ 1234567 ) (mod 98765432109) == 56817909189

vijayan

View Public Profile

Find all posts by vijayan

#7

05-09-2009, 05:03 AM

Join Date: May 2007


Peter_APIIT
Posts: 842
Registered User

Why

Code:

// ( a * b ) (mod m ) == ( ( a (mod m) ) * ( b (mod m) ) ) (mod m)


BigUnsigned number = base % modulus ;
number need to initialized with base % modulus >?

Thanks.

Peter_APIIT

View Public Profile

Find all posts by Peter_APIIT

Bookmarks
• Digg

• del.icio.us

• StumbleUpon

• Google

« Previous Thread | Next Thread »

Top of Form
Thread Tools

Show Printable Version

Email this Page

Bottom of Form
Display Modes

Linear Mode

Switch to Hybrid Mode

Switch to Threaded Mode

Top of Form
Rate This Thread

Excellent

Good

Average
Bad

Terrible

bdd8eeeaa75421 guest 172020 15 1

Bottom of Form
Top of Form
Posting Rules bdd8eeeaa75421

Fo
You may not post new threads rum Jump

You may not post replies C++

You may not post attachments


Go
You may not edit your posts

Bottom of Form
BB code is On

Smilies are Off

[IMG] code is Off

HTML code is Off

Similar Threads

Thread Thread Starter Forum Replies Last Post

Karatsuba Wrong Answer After 6 05-06-2009 10:28


Peter_APIIT C++ 4
Decimal digits AM

09-19-2008 07:29
Padding left or Margin left? pityocamptes ASP.NET 6
AM

03-18-2002 10:25
Long, basic Java Question. Tom Java 0
AM

09-07-2001 06:19
Why is this not binary compatible Kip Fryman VB Classic 2
AM

All times are GMT -4. The time now is 08:13 AM.

Top of Form
Contact Us - DevX.com - Archive - Top
World's Fastest Object Database.

Open API Service: It takes the right tools to make an app a success.
Learn more.

Dollars for Downloads! Make an extra $2 per download with the Intel®
Atom™ Developer Program

Join the Intel® Atom™ Developer Program—create apps to sell


worldwide

Looking for a reliable printer that also copies, scans, and faxes? Click
here.

Advertising Info | Permissions | Help | Site Map | Network Map | About

Acceptable Use Policy


The Network for Technology Professionals
Top of Form
1 0 10 50 all

Search:

Bottom of Form

About Internet.com
Copyright 2010 QuinStreet Inc. All Rights Reserved.

Legal Notices, Licensing, Permissions, Privacy Policy.


Advertise | Newsletters | E-mail Offers

Powered by vBulletin® Version 3.7.3


Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.

Bottom of Form

Vous aimerez peut-être aussi