C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 10-31-2009, 10:17 AM   #1
Registered User
 
Join Date: Jan 2009
Posts: 65
Discrete Math

I know that this isn't a math forum .. but i have always found help here so i am posting something again

Given:
Code:
N  ,  M  ,  K  ,  gcd(a,b)=1

N,M can be written as
N = a + b
M = a^2 + b^2 - (2^K - 2) * a * b

Note: a,b are not given
N ,M ~ 10^400
Find gcd(N,M)

Now for this i write a brute force code and i always get gcd as a power of two
i.e
gcd(N,M)=2^z

Hence for finding gcd i use a loop each time multiplying the gcd by 2 and checking if( N%gcd==0 && M%gcd===0 )
But this still ain't fast enough !

Is there any way to compute the gcd faster ??

Thanks
jack_carver is offline   Reply With Quote
Old 10-31-2009, 10:26 AM   #2
The superheterodyne.
 
twomers's Avatar
 
Join Date: Dec 2005
Location: Ireland
Posts: 2,220
Are gcd's always powers of any other numbers? 4? 8? 16? 32?
Do a log to the base 4/16 etc over all the gcd elements and see if you get whole number results.
__________________
I blag!
twomers is offline   Reply With Quote
Old 10-31-2009, 10:35 AM   #3
Registered User
 
Join Date: Jan 2009
Posts: 65
Re

I dont know what u meant but this is my current code
Code:
#include <cstdio>
#include <cstring>
using namespace std;

bool mod(const char *str,int num) //check if str%num==0
{
	int i,len=strlen(str),res=0;
	
	for(i=0;i<len;i++)
	{
		res=10*res+str[i]-'0';
		res%=num;
	}
	return res==0;
}

int main()
{
	int cases,K,gcd,temp;
	char N[1005],M[1005];
	
	
	scanf("%d",&cases);
	while(cases--)
	{
		scanf("%s %s %d",N,M,&K);
		
		gcd=1;
		temp=1;
		
		while(1)
		{
			if(mod(N,temp) && mod(M,temp))gcd=temp;
			else break;	
			temp*=2;
		}
		printf("%d\n",gcd);
	}
	return 0;
}
jack_carver is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Math knightjp General Discussions 16 04-01-2009 05:36 PM
Basic Math Problem. Undefined Math Functions gsoft C Programming 1 12-28-2004 03:14 AM
Discrete Math question theoddmonkey Tech Board 2 07-01-2004 08:41 AM
toughest math course axon A Brief History of Cprogramming.com 12 10-28-2003 10:06 PM
Discrete Math rickc77 A Brief History of Cprogramming.com 4 02-19-2002 11:43 AM


All times are GMT -6. The time now is 12:12 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

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