ZONE
FEATURES
Home
News
Check Email
LEARNING ZONE
C++ Tutorial
Tutorials collection
Ask the Expert
FAQs
Refferences
ARTICLES
All articles
DOWNLOADS
Compilers
Sourcode Library
Tools/Utilities
WINDOWS
Win programing
C++ Builder
UNIX
Unix programming
Unix downloads
WEB PROGRAMMING
CGI programming
CGI Scripts
RESOURCES
Magazines
Newsletters
Mailing Lists
Courses
Links
COMMUNICATION
Message board
Chat
Communities
Organisations
C++ Groups
C++ Newsgroups
ABOUT US
Contact us
submit a resource
Privacy
Link to us
 
 
 
Home Ask the expert printf
 

Ask me a question

Main Q & A Page
 
SUBJECT : The Necklace problem

An interesting problem in number theory is sometimes called the "necklace problem." This problem beings with two single-digit numbers. The next number is obtained by adding the first two numbers toegether and saving only the ones-digit. This process is repeated until the "necklace" closes by returning to the original two number.

Here is a possible code for solving this problem:

#include int main()
 {
   int Number1, Number2;
   cout << "Enter first number:  ";
   cin >> Number1;
  
   cout << "Enter second number: ";
   cin >> Number2; cout <<  Number1 << " " << Number2;
   int Sum = Number1 + Number2;
   int NextNumber = Sum % 10;
   cout << " " << NextNumber;
   int PreviousNumber = Number2; int Steps = 1; 
   while ((PreviousNumber != Number1) && (NextNumber != Number2))
    {
     Steps++; Sum = NextNumber + PreviousNumber;
     PreviousNumber = NextNumber;
     NextNumber = Sum % 10;
     cout << " " << NextNumber;
    }
   cout << "\nYour numbers required " << Steps  << " steps." << endl; return(0); }
.... in the line "while ((PreviousNumber != Number1) || (NextNumber != Number2))", why is it || (or) instead of && (and) seeing that both numbers need to match up with the two original numbers? Please get back to us ASAP! Thank you!
     
Sender : Jonathan Riddell  
 
Reply1

The != means not equal to.
So the statement: while((PreviousNumber != Number1) || (NextNumber != Number2)) is saying,
if PreviousNumber is not equal to Number1 or NextNumber is not equal to Number2 continue with generating the necklace.

It is a more efficient statement than: while(!((PreviousNumber == Number1) && (NextNumber == Number2))) because it can fail if the first comparision is false without having to needlessly perform the second comparision....

Its a well known theorem, In general (A or B) has the same value as /( /A and /B).
That's DeMorgan's theorem:

(A and B) = A or B
(A or B) = A and B

where = NOT

if my mind serves me correctly, and then you can apply to it to get:-

(A and B) = (A or B)
=> (A and B) = (A or B)

similarly for (A or B) Ian

Sender : D.O  
 
 
 
 

Ask me a question

Main Q & A Page
 
 
A
Email Login
Password
New?
sign up!
 
A
Free Online tutorial & courses
 
A
Join Our Message board Discussions on C/C++
 
A
Unix Network
programming
tutorial
 
 Join Our Mailing list