Académique Documents
Professionnel Documents
Culture Documents
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
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
• Tech News »
• Programming Discussions for Engineers »
• Find the greatest common divisor of 2 numbers a and b and also find 2 numbers x
« previous next »
• Reply
Pages: [1]
sams.raghu
• 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.
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;
}
return gcd;
}
Logged
Bottom of Form
• Reply
• Print
• Register to comment on this topic
Pages: [1]
« previous next »
• Tech News »
• 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
Jump to:
Related Topics
Subject / Started by Replies Last post
Bottom of Form
Top of Form
Bottom of Form
Top of Form
partner-pub-0153 ISO-8859-1 Search
Bottom of Form
Top of Form
Bottom of Form
#include<stdio.h>
int main(){
int n1,n2;
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:
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;
m=x
for(i=m;i>=1;i--){
if(x%i==0&&y%i==0){
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...
6/18/10 6:31 PM
Anonymous said...
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
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
Subscribe To
Posts
Atom
Posts
Comments
Atom
Comments
Standard of questions ?
Pages
• Home
C lover community
/*
*/
#include <stdio>
if(b==0)
return a;
else
return euclid(b,a%b);
int main()
int n1,n2;
scanf("%d %d",&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.
9. if(b==0)
10. return a;
11. else
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.
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
Ads by Google
Permalink
Perhaps you should try the original divised by the greek Euclid :
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 */
/*
* 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;
/* recurse */
sort(&l[1], lsz-1);
}
int main(void)
{
int i; /* counter in a for loop */
/* now sort */
sort(list, nlist);
Factorial recursive
#include<stdio.h>
main()
int a, fact;
fact=rec (a);
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();
}
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;
fibNum = fib(i); /*figure out the fib number of the given value ("i")*/
}
return 0;
Top of Form
Bottom of Form
Views: 2,843
Language: C
Instructions: Implement when you need to solve this type of problem iteratively rather then
recursively.
Snippet
6. int fib(int n)
7. {
8. int f2=0;
9. int f1=1;
11. int i;
12.
13. if (n==0 || n==1)
14. return n;
15. for(i=2;i<=n;i++){
19. }
26. int i;
27.
29. fibNum = fib(i); /*figure out the fib number of the given value
("i")*/
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 of Form
process 0
simplesearch
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
Search Forums
Top of Form
process 1 1 1 bdd8eeeaa75421 guest
Go
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
Hello to all, i try to code the binary exponentiation algorithm but unfortunately it is not
working as desire.
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 current code.
Code:
Code:
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;
}
return result;
}
Thanks.
Peter_APIIT
#2
05-05-2009, 11:14 PM
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
#3
05-06-2009, 06:33 AM
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.
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.
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;
exponent <<=1;
Thanks for your explanation.
Thanks.
Last edited by Peter_APIIT; 05-06-2009 at 07:59 AM. Reason: Add some information
Peter_APIIT
#4
05-07-2009, 01:52 PM
Code:
#include <string>
#include <iostream>
#include <bitset>
#include <limits>
#include "BigIntegerLibrary.hh"
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
#5
05-08-2009, 03:40 AM
if (bitExponent[MSSBPos] == '1')
{
result = (result * base);
}
++MSSBPos;
}
}
return result;
}
Thanks.
Peter_APIIT
05-08-2009, 07:31 AM
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"
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
#7
05-09-2009, 05:03 AM
Why
Code:
Thanks.
Peter_APIIT
Bookmarks
• Digg
• del.icio.us
• StumbleUpon
Top of Form
Thread Tools
Bottom of Form
Display Modes
Linear Mode
Top of Form
Rate This Thread
Excellent
Good
Average
Bad
Terrible
Bottom of Form
Top of Form
Posting Rules bdd8eeeaa75421
Fo
You may not post new threads rum Jump
Bottom of Form
BB code is On
Similar Threads
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
Looking for a reliable printer that also copies, scans, and faxes? Click
here.
Search:
Bottom of Form
About Internet.com
Copyright 2010 QuinStreet Inc. All Rights Reserved.
Bottom of Form