Re: 3n+1 problem of acm
- From: Michael Mair <Michael.Mair@xxxxxxxxxxxxxxx>
- Date: Sun, 30 Apr 2006 19:50:13 +0200
sathyashrayan schrieb:
Dear group,
The below given link which I want to implement in C.
http://online-judge.uva.es/p/v1/100.html
The code which I wrote does not even reaches the near to the
given problem.(I am just learning)
#include<stdio.h>
#include<stdlib.h>
unsigned evn,odd;
void odd_evn(unsigned int number)
{
if((number % 2) == 0)
{
evn = 1;
odd = 0;
}
evn = 0;
odd = 1;
This code always executes the last two statements.
Either put this part into an else branch or directly compute
evn and odd via
odd = ((number % 2) != 0);
evn = 1 - odd;
or similar.
}
int main(int argv, char *argc[])
You changed the usually used main parameter identifiers.
It's
int main (int argc, char **argv)
This is perfectly legal but may irritate or confuse people
reading your code.
{
unsigned long n;
unsigned int i,j;
unsigned int has a minimal maximum value of 65535 -- this
is not enough for the task at hand. Use unsigned long values.
int counter=0;
if(argv == 0 && argv >=3)
This is never true.
Make it
if (argv != 3)
{
printf("eror\n");
exit(EXIT_FAILURE);
}
i=atoi(argc[1]);
j=atoi(argc[2]);
atoi() is not exactly the safest input function; in addition,
it does not guaranteedly cover the range discussed. Read up on
the use of strtoul().
for(n=i; n<j;n++)
{
Within this loop, you are supposed to determine the cycle length
for every number from i to j, including i and j.
odd_evn(n);
if(odd == 1 && evn == 0)
n = (3 * n) + 1;
if(odd == 0 && evn == 1)
n = n / 2;
What a mess.
You obviously do not need evn at all as evn always is 1-odd;
this is the second, unnecessary, check you are performing for
every if.
In addition, the two if conditions are mutually exclusive.
if (odd)
n = (3 * n) + 1;
else
n = n/2;
counter++;
printf("%lu and %d\n",n, counter);
You misunderstood the task.
}
return 0;
}
Once the n gets the even number it just divides it by two
and, at the end n reaches with even number and terminates.
Can any one give me some clue or hint for correct implementation.
of the above?
unsigned long max = 0;
unsigned long index;
unsigned long cycle_length;
for (index = i; index <= j; index++) {
cycle_length = determine_cycle_length(index);
if (cycle_length > max) {
max = cycle_length;
}
}
printf("%lu %lu %lu\n", i, j, max);
matches the requirements from the link. Now just implement
determine_cycle_length along the given algorithm.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
.
- References:
- 3n+1 problem of acm
- From: sathyashrayan
- 3n+1 problem of acm
- Prev by Date: Re: help me learn C
- Next by Date: Re: Function Signatures In time.h
- Previous by thread: 3n+1 problem of acm
- Next by thread: Re: 3n+1 problem of acm
- Index(es):
Relevant Pages
|