473,883 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fibonacci number

How to generate fibonacci mubers in C ?
Nov 14 '05
62 5470
la************@ ugsplm.com wrote:
In comp.std.c CBFalconer <cb********@yah oo.com> wrote:

That makes no sense to me. If -2 is handled with modulo
arithmetic, so should a string representing ULONG_MAX + 2.


Why? Consider the following:

/* assuming ULONG_MAX == 4294967295 */
unsigned long ul1 = -2UL; // perfectly good, ul1 = 4294967294
unsigned long ul2 = 4294967297UL; // error, overflow


The first is actually -(2UL), which has been specifically defined
to be interpreted with modulo arithmetic. However the string "-2"
represents a value outside the range of an unsigned long. The
purpose of error detection in strtoul() is to detect the supply of
an invalid value by the user.

I would suggest that the proper interpretation of that string is
to set endptr to point after the 2 (which may be to a '\0'),
return ULONG_MAX, and set errno to ERANGE.

To achieve the modulo interpretation, the programmer should have
to write:

unsigned long u;

u = -2;
or
u = strtol("-2", NULL, 10);

which last will have exactly the same values to use in the actual
assignment.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #21
CBFalconer wrote:
... the string "-2"
represents a value outside the range of an unsigned long. The
purpose of error detection in strtoul() is to detect the supply of
an invalid value by the user.

I would suggest that the proper interpretation of that string is
to set endptr to point after the 2 (which may be to a '\0'),
return ULONG_MAX, and set errno to ERANGE.


Basically, the argument is for a change of the standard to disallow the
optional - sign. I agree, and Doug implied earlier that such an
interpretation would make sense if we start defining the strtoul
function from scratch. Since that would be a quiet change for working
programs that don't check ERRNO, and it is easy to avoid in the program
by testing, I don't expect it to fly.

Another example: application programs which accept 012 as a user input
and convert to 10, not the intended 12.

I chalk both problems up to baggage that C carries around because it is
has a legacy. The practical alternatives are to add your own checks or
to use non-Standard-C robust input routines.

Thad
Nov 14 '05 #22
Thad Smith wrote:

CBFalconer wrote:
... the string "-2"
represents a value outside the range of an unsigned long. The
purpose of error detection in strtoul() is to detect the supply of
an invalid value by the user.

I would suggest that the proper interpretation of that string is
to set endptr to point after the 2 (which may be to a '\0'),
return ULONG_MAX, and set errno to ERANGE.


Basically, the argument is for a change of the standard to disallow the
optional - sign. I agree, and Doug implied earlier that such an
interpretation would make sense if we start defining the strtoul
function from scratch. Since that would be a quiet change for working
programs that don't check ERRNO, and it is easy to avoid in the program
by testing, I don't expect it to fly.


Well, not quite. I am willing to face the idea that - signs are
accepted on input, and that the string is then parsed up to the
first non-digit (per base). I could even be persuaded to accept
the modulo arithmetic. But errno should be set to ERANGE for all
of them. Then it is possible to detect user errors. The routine
can be used as the basis for strtol in addition.

As it is I cannot use strtoul to input from somewhere, and either
write out the same value or announce some form of input error.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #23
nrk
CBFalconer wrote:
Thad Smith wrote:

CBFalconer wrote:
> ... the string "-2"
> represents a value outside the range of an unsigned long. The
> purpose of error detection in strtoul() is to detect the supply of
> an invalid value by the user.
>
> I would suggest that the proper interpretation of that string is
> to set endptr to point after the 2 (which may be to a '\0'),
> return ULONG_MAX, and set errno to ERANGE.


Basically, the argument is for a change of the standard to disallow the
optional - sign. I agree, and Doug implied earlier that such an
interpretation would make sense if we start defining the strtoul
function from scratch. Since that would be a quiet change for working
programs that don't check ERRNO, and it is easy to avoid in the program
by testing, I don't expect it to fly.


Well, not quite. I am willing to face the idea that - signs are
accepted on input, and that the string is then parsed up to the
first non-digit (per base). I could even be persuaded to accept
the modulo arithmetic. But errno should be set to ERANGE for all
of them. Then it is possible to detect user errors. The routine
can be used as the basis for strtol in addition.

As it is I cannot use strtoul to input from somewhere, and either
write out the same value or announce some form of input error.


You have the input in the first place. All you'd have to do is check the
first character for a '-' (for the specific case you mention), once you get
a return and check endptr and errno for other possible errors in the input.
This doesn't seem too unreasonable to me, once you take the step of
accepting modulo arithmetic from strtoul.

-nrk.

--
Remove devnull for email
Nov 14 '05 #24
nrk wrote:
CBFalconer wrote:
Thad Smith wrote:
CBFalconer wrote:

> ... the string "-2"
> represents a value outside the range of an unsigned long. The
> purpose of error detection in strtoul() is to detect the supply of
> an invalid value by the user.
>
> I would suggest that the proper interpretation of that string is
> to set endptr to point after the 2 (which may be to a '\0'),
> return ULONG_MAX, and set errno to ERANGE.

Basically, the argument is for a change of the standard to disallow
the optional - sign. I agree, and Doug implied earlier that such
an interpretation would make sense if we start defining the strtoul
function from scratch. Since that would be a quiet change for
working programs that don't check ERRNO, and it is easy to avoid in
the program by testing, I don't expect it to fly.


Well, not quite. I am willing to face the idea that - signs are
accepted on input, and that the string is then parsed up to the
first non-digit (per base). I could even be persuaded to accept
the modulo arithmetic. But errno should be set to ERANGE for all
of them. Then it is possible to detect user errors. The routine
can be used as the basis for strtol in addition.

As it is I cannot use strtoul to input from somewhere, and either
write out the same value or announce some form of input error.


You have the input in the first place. All you'd have to do is check
the first character for a '-' (for the specific case you mention),
once you get a return and check endptr and errno for other possible
errors in the input. This doesn't seem too unreasonable to me, once
you take the step of accepting modulo arithmetic from strtoul.


It is not quite that simple. You also have to scan off any
leading blanks, and possibly all leading white space. And if "-2"
is a legal input field for strtoul, what about "--2"?

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #25
In article <news:40******* ********@yahoo. com>
CBFalconer <cb********@wor ldnet.att.net> writes:
It is not quite that simple. You also have to scan off any
leading blanks, and possibly all leading white space.
True (provided you do want to allow leading whitespace;
otherwise a simple isdigit() test will suffice for bases
up to 10). If you are in the C locale and have a pointer
to the start of the string, you can skip whitespace with:

s += strspn(s, " \t\n\r\f\v\b");
And if "-2" is a legal input field for strtoul, what about "--2"?


Read the strtoul() specification (or below).

This text is from the BSD/OS strtol() manual page:

The string may begin with an arbitrary amount of white space (as deter-
mined by isspace(3)) followed by a single optional `+' or `-' sign. If
base is zero or 16, the string may then include a `0x' prefix, and the
number will be read in base 16; otherwise, a zero base is taken as 10
(decimal) unless the next character is `0', in which case it is taken as
8 (octal).
...
Upon success the strtoul() and strtoull() functions return either the re-
sult of the conversion or, if there was a leading minus sign, the nega-
tion of the result of the conversion, unless the original (non-negated)
value would overflow. In the case of an overflow the functions return
ULONG_MAX and UQUAD_MAX respectively and the global variable errno is set
to ERANGE.

(Note that C99 uses ULLONG_MAX, not UQUAD_MAX. Our strtoull()
predates C99 and was originally spelled strtoq(). I originally
wrote this manual page for 4.3BSD, where we used "quad_t" as the
name for 64-bit integers starting in the early 1990s.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #26
nrk
CBFalconer wrote:
nrk wrote:
CBFalconer wrote:
> Thad Smith wrote:
>> CBFalconer wrote:
>>
>> > ... the string "-2"
>> > represents a value outside the range of an unsigned long. The
>> > purpose of error detection in strtoul() is to detect the supply of
>> > an invalid value by the user.
>> >
>> > I would suggest that the proper interpretation of that string is
>> > to set endptr to point after the 2 (which may be to a '\0'),
>> > return ULONG_MAX, and set errno to ERANGE.
>>
>> Basically, the argument is for a change of the standard to disallow
>> the optional - sign. I agree, and Doug implied earlier that such
>> an interpretation would make sense if we start defining the strtoul
>> function from scratch. Since that would be a quiet change for
>> working programs that don't check ERRNO, and it is easy to avoid in
>> the program by testing, I don't expect it to fly.
>
> Well, not quite. I am willing to face the idea that - signs are
> accepted on input, and that the string is then parsed up to the
> first non-digit (per base). I could even be persuaded to accept
> the modulo arithmetic. But errno should be set to ERANGE for all
> of them. Then it is possible to detect user errors. The routine
> can be used as the basis for strtol in addition.
>
> As it is I cannot use strtoul to input from somewhere, and either
> write out the same value or announce some form of input error.


You have the input in the first place. All you'd have to do is check
the first character for a '-' (for the specific case you mention),
once you get a return and check endptr and errno for other possible
errors in the input. This doesn't seem too unreasonable to me, once
you take the step of accepting modulo arithmetic from strtoul.


It is not quite that simple. You also have to scan off any
leading blanks, and possibly all leading white space. And if "-2"
is a legal input field for strtoul, what about "--2"?


Right. Let's take this one thing at a time. "--2", we know, according to
specification, doesn't qualify as an integer for either strtol or strtoul
since both allow exactly *one* optional sign preceding the number (see my
recent thread on a broken implementation of strtol that doesn't grok this
correctly). So, if we do use endptr correctly to track the call to
strtoul, this case will be handled.

Let's take the case of leading spaces. I had forgotten all about them in my
initial remedy to check for a '-' sign. Chris has pointed out how you can
skip leading white space if any. However, turns out that things are much
simpler than that if you merely wish to detect the presence of the '-'.
Use strchr and check the return against NULL and endptr! Thusly, we can
come up with something along the lines of (it is even simpler if the entire
string is supposed to be converted):

unsigned long safe_strtoul(co nst char *src, char **endptr, int base) {
unsigned long ret;
int old_errno = errno;
char *cptr;

errno = 0;
ret = strtoul(src, endptr, base);

if ( errno )
return ret; /* lets not bother checking anything */

if ( src == *endptr ) {
/* no conversion, throw back at user */
errno = old_errno;
return ret;
}

cptr = strchr(src, '-');
if ( cptr && cptr < *endptr ) {
/* conversion, but there was a '-' at start */
errno = ERANGE;
return ULONG_MAX;
/* I think at this point we've achieved the CBF strtoul */
}

errno = old_errno;
return ret;
}

-nrk.

--
Remove devnull for email
Nov 14 '05 #27
Thad Smith wrote:
Another example: application programs which accept 012 as a user input
and convert to 10, not the intended 12.
I chalk both problems up to baggage that C carries around because it is
has a legacy.


And some of that legacy has origins that predate Unix and C.
One saw 012 = 10. and ASCIZ (null-terminated) strings in DEC
software well before C appeared.

Nov 14 '05 #28
CBFalconer wrote:
As it is I cannot use strtoul to input from somewhere, and either
write out the same value or announce some form of input error.


Sure you can, you just have to do part of the checking
that you seem to want for your application yourself.

Really good input checking and validation requires much
more than any Standard C library function provides.

Nov 14 '05 #29
In <AY************ ********@comcas t.com> "Douglas A. Gwyn" <DA****@null.ne t> writes:
Really good input checking and validation requires much
more than any Standard C library function provides.


And this is a deficiency of the C standard that the committee doesn't
bother to fix. Why should each robust C application have to invent its
own wheel?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
13133
by: dleecurt | last post by:
Hello, I have a small problem, I am trying to write a program that will calculate the Fibonacci number series, and I have the code complete with one problem. I used a long in to store the numbers, and when the numbers get too large it maxes out the int and I can't count any higher. I am trying to use extremely large numbers, I would like to use up to 10^50 or so. So my question is how do I do this? I'm just learning the language and I...
5
7749
by: Niks | last post by:
Can anybody explain me what is a "Fibonacci search"? even an URL will do. Thanks for reading.
4
4878
by: YS Sze | last post by:
If you know the exact longitude and latitude for a specific location, would anyone think it'd make any sense to find out if this set of location numbers is really part of the Fibonacci series or not? Or, another way to look at this is that: Would anyone of you think it is worth a while to find out if there is any location on earth with the set of longitude and latitude numbers that coincides with the Fibonacci series? As I see it, if...
14
4955
by: felixnielsen | last post by:
Im actually kinda embarassed to ask this question... @code start #include <iostream> int main() { unsigned long long a = 1; unsigned long long b = 1; for (int i = 0; i < 45; i++) { a += b; std::cout << a/b << std::endl;
12
1917
by: Santosh Krisnan | last post by:
hello all, I fiddled with BASIC in the early 90s but left it at that. Now I am trying to learn C. I tried to solve an exercise in my book, but it failes to compile. Can anyone tell me what the error messages mean & what I should do? thanks.
13
3184
by: mac | last post by:
Hi, I'm trying to write a fibonacci recursive function that will return the fibonacci string separated by comma. The problem sounds like this: ------------- Write a recursive function that creates a character string containing the first n Fibonacci numbers - F(n) = F(n - 1) + F(n - 2), F(0) = F(1) = 1 -, separated by comma. n should be given as an argument to the program. The recursive function should only take one parameter, n, and...
6
4980
by: Andrew Tatum | last post by:
I'm having some problems with the below equation. I have no problems when it comes to positives. Negatives create the problem.. C 2 1 4 However, this doesn't work:
7
2002
by: ssecorp | last post by:
I am not clear about the results here. from timeit import Timer import Decorators def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1
1
8844
by: altaey | last post by:
Question Details: Write a program to find and print a Fibonacci sequence of numbers. The Fibonacci sequence is defined as follow: Fn = Fn-2 + Fn-1, n >= 0 F0 = 0, F1 = 1, F2 = 1 Your program should prompt the user to enter a limit and indicate whether the last number in the sequence printed is either even or odd.
0
9932
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11109
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10728
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9558
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5980
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4602
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3227
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.