473,836 Members | 1,572 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 5462
Dan Pop wrote:
CBFalconer <cb********@yah oo.com> writes:
Apart from exponential notation for reals, I see no problem
building iron-clad numeric input parsers with one-char look
ahead.


Dealing with overflow without invoking undefined behaviour is
the most challenging part.


Something along the lines of:

overflow = partial = 0;
while (getavaliddigit ()) {
.... form input digit ....
if ((partial < CRITERION) ||
(MAX - digit) / base) <= partial))
partial = base * partial + digit;
else {
overflow = 1;
partial = MAX;
}
}
putback(ch); /* beware complications from EOF and unget */

does not require any hardware overflow detection, and will gobble
up a stream of digits.

--
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 #51
"Wojtek Lerch" <Wo******@yahoo .ca> wrote:
"P.J. Plauger" <pj*@dinkumware .com> wrote in message
news:L3******** **********@nwrd dc01.gnilink.ne t...
"CBFalconer " <cb********@yah oo.com> wrote in message
news:40******** *******@yahoo.c om...
have no problems with needing to design such routines, but I do
have problems with suddenly finding out that it is necessary.
Especially when the only change really needed is to ban the
leading sign.


Or skip it yourself. Why is that so hard?


Because you might not have a guarantee that the current locale is "C"?

It seems reasonable that in other locales, strtoul() might recognize
additional spellings of the negative sign, or accept the sign after the
digits. How do I tell the difference between 2 and -4294967294 then?


7.20.1.4 #6: In other than the "C" locale, additional locale-specific
subject sequence forms may be accepted.

IOW, if you're not in the "C" locale, you don't know jack about the
subject sequence anyway, so there's no way for you to tell whether
_anything_ is positive or negative - but more importantly, you don't
even know if anything is an integer in the first place.

But there's still a reasonable way around this: _first_ scan the string
with strtol(). If the result is negative, the subject sequence contained
a minus sign; this is true regardless of whether the number fits a long,
because on negative overflow, strtol() returns LONG_MIN, which is also
negative.

Richard
Nov 14 '05 #52
In <40************ ***@null.net> "Douglas A. Gwyn" <DA****@null.ne t> writes:
Dan Pop wrote:
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?


What constitutes really good input checking and validation
is heavily application-dependent.


When dealing with numeric input, all applications have the same
requirements: the input was correct according to the specifications of
the corresponding type. If the application wants further restrictions
(e.g. values in a subrange of type_MIN..type_ MAX), these can be
trivially implemented once you know the input was valid for its
intended type.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #53
In <c1**********@s unnews.cern.ch> Da*****@cern.ch (Dan Pop) writes:
Actually, scanf is quite good and well designed. I have only two
complaints about it:

1. Undefined behaviour on numeric input overflow. Making the conversion
fail would have been a lot more useful.

2. No escape sequence for specifying a null character in a scanset (\0
would terminate the format string).


I somehow forgot the third one: no way to dynamically specify maximum
field widths, like the asterisk in printf formats.

The workaround is to build the whole format string at run time, but
this destroys the code readability, because you have to imagine how
the format string would look like, instead of simply looking at it.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #54
In article <mA************ *******@nwrddc0 1.gnilink.net>,
P.J. Plauger <pj*@dinkumware .com> wrote:
Safety tip: Use 10 as the third (base) argument to strtoul


And not 010 :-)

-- Richard
--
Spam filter: to mail me from a .com/.net site, put my surname in the headers.

FreeBSD rules!
Nov 14 '05 #55
In <mv************ @jones.homeip.n et> la************@ ugsplm.com writes:
In comp.std.c P.J. Plauger <pj*@dinkumware .com> wrote:

Safety tip: Use 10 as the third (base) argument to strtoul, so 012
converts to 12. Don't use 0 as the base argument, since that's the
*only* form that lets the input prefix determine the base.


But again, that's application dependent. For some applications, being
able to input octal or hex in addition to decimal is definitely a
feature, not a bug.


This whole subthread was started by the complaint that 012 is interpreted
as an octal number, which I failed to understand.

If you don't want this to happen, use base 10 and it won't happen.
If you use "base" 0, it is precisely because you want this to happen.

Programs using "base" 0 should warn the users about the expected input
formats and their semantics.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #56
Richard Bos wrote:
"Wojtek Lerch" <Wo******@yahoo .ca> wrote:
It seems reasonable that in other locales, strtoul() might recognize
additional spellings of the negative sign, or accept the sign after the
digits. How do I tell the difference between 2 and -4294967294 then?
7.20.1.4 #6: In other than the "C" locale, additional locale-specific
subject sequence forms may be accepted.

IOW, if you're not in the "C" locale, you don't know jack about the
subject sequence anyway, so there's no way for you to tell whether
_anything_ is positive or negative - but more importantly, you don't
even know if anything is an integer in the first place.


Exactly: all I can possibly know is what strtoul() tells me. If
strtoul() tells me that the string a person entered is a
representation of the number 2 in the current locale, I have no choice
but to trust that.

Unless, of course, I parse the string myself and notice that it's
"-4294967294". But if I'm not in the "C" locale, I have no reliable
way of catching all such misunderstandin gs.
But there's still a reasonable way around this: _first_ scan the string
with strtol(). If the result is negative, the subject sequence contained
a minus sign; this is true regardless of whether the number fits a long,
because on negative overflow, strtol() returns LONG_MIN, which is also
negative.


That's a nice idea, but I think it might not work with some
conceivable (albeit wierd) implementations . Imagine, for instance,
that in some locale, the additional forms of subject sequences contain
a prefix that specifies whether the number is signed negative, signed
non-negative, or unsigned, and strtol() rejects the unsigned ones as
invalid. Wouldn't that be conforming?
Nov 14 '05 #57
Wo******@yahoo. ca (Wojtek Lerch) wrote:
Richard Bos wrote:
But there's still a reasonable way around this: _first_ scan the string
with strtol(). If the result is negative, the subject sequence contained
a minus sign; this is true regardless of whether the number fits a long,
because on negative overflow, strtol() returns LONG_MIN, which is also
negative.


That's a nice idea, but I think it might not work with some
conceivable (albeit wierd) implementations . Imagine, for instance,
that in some locale, the additional forms of subject sequences contain
a prefix that specifies whether the number is signed negative, signed
non-negative, or unsigned, and strtol() rejects the unsigned ones as
invalid. Wouldn't that be conforming?


I'm not sure, but I doubt it. Even if it is, when it returns a negative
value, the subject sequence is signed negative. Invalid subject
sequences must return 0.

Richard
Nov 14 '05 #58
Richard Bos wrote:
Wo******@yahoo. ca (Wojtek Lerch) wrote:
Richard Bos wrote:
But there's still a reasonable way around this: _first_ scan the string
with strtol(). If the result is negative, the subject sequence contained
a minus sign; this is true regardless of whether the number fits a long,
because on negative overflow, strtol() returns LONG_MIN, which is also
negative.


That's a nice idea, but I think it might not work with some
conceivable (albeit wierd) implementations . Imagine, for instance,
that in some locale, the additional forms of subject sequences contain
a prefix that specifies whether the number is signed negative, signed
non-negative, or unsigned, and strtol() rejects the unsigned ones as
invalid. Wouldn't that be conforming?


I'm not sure, but I doubt it. Even if it is, when it returns a negative
value, the subject sequence is signed negative. Invalid subject
sequences must return 0.


Sorry, that wasn't a very good example... But what about this one: a
suffix that is interpreted as a negative sign by strtol(), but not
recognized by strtoul(). Can you find any words in the standard that
forbid this?...
Nov 14 '05 #59
Wo******@yahoo. ca (Wojtek Lerch) wrote:
suffix that is interpreted as a negative sign by strtol(), but not
recognized by strtoul(). Can you find any words in the standard that
forbid this?...


Not words, exactly, but it does seem to imply that. All four of
strtol(), strtoul(), strtoll() and strtoull() share a paragraph, and
that paragraph mentions "the" subject sequence, singular. The only
difference that is explicitly mentioned is that between the type to
which these functions convert the subject sequence.

Richard
Nov 14 '05 #60

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

Similar topics

28
13131
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
7748
by: Niks | last post by:
Can anybody explain me what is a "Fibonacci search"? even an URL will do. Thanks for reading.
4
4873
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
4950
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
1915
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
3180
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
4979
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
8842
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
10840
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...
1
10588
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
10254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9371
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...
1
7790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6978
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5647
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4448
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
3
3112
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.