Jump to content

How to write it in C++?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
saurav

saurav

    Newbie

  • Members
  • Pip
  • 8 posts
Consider the problem:

f(n) is a sequence, with integral values.
A sequence x(n) with integral values is said to have the property A(x) iff
for all n<12, 5n< x(n)< 7n-9.
We are to decide whether or not f(n) has the property A(f), where f(n) are given for n =1 to n = 15.

The property A(x) may be more complex, for example,
A(x) : forall n <12, x(n) is prime.

How to write it in c++?

Thanks.

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
You'll need a loop (while loop, since there may not be 12 elements) and test each element in the loop. You'll also need a boolean to act as a flag in case you find a violation. More complicated criteria will require additional coding, such as a test for primality.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
kkelly

kkelly

    Learning Programmer

  • Members
  • PipPipPip
  • 49 posts
So for each n there is a sequence f(n)? If so then . . .

Since f(n) is a sequence of undetermined length. You'll need to allocate memory dynamically, so you will need a linked list. I'd make the function a class with a structure call Values that is a linked list representing the sequence. The class would take n as a constructor parameter. Remember to delete your nodes in your destructor!
In your main.cpp module, create a function to represent A(x). It would be a boolean type and implement a recursive structure. Something like:


#include "Fof.h"

 

//	n is the high value you are testing.  I.E. for n<12, n = 11.

bool HasProperty(unsigned int n)

{

	//	If n equals zero we have tested all our positive integers

	if (n == 0)

	{

		return true;

	}

	else

	{	

		//  Create our function with n as the parameter

		Fof Xof(n);

		//	while there are values in the sequence

		while (Xof.ValuesPtr != Null)

		{

			//	If our criteria is not met

			if (Xof.ValuesPtr->value <= (5*n) || Xof.ValuesPtr->value >= (7*n) - 9 || n >= 12)

			{

				return false;

			}

			else

			{

				//	move to the next value in the sequence

				Xof.ValuePtr = Xof.ValuePtr->next;

			}

		}

		//	decrement n

		n--;

		//	keep testing

		return HasProperty(n);

	}

}