mrnutty 761 Senior Poster

Oh wait another option , via Newton. Its a good approx.
It has similar logic as above, but the heat of the program relies on
calculus, which is done on paper.

double Sqrt(double Num)
{
	double i = 2;		
	double Result = 0;
	unsigned int Precision = 10;
	for(int j = 0; j <Precision ; j++)
	{
		Result = i - (i*i - Num) / (2.0*i);		
		i = Result;
	}
	return Result;
}
mrnutty 761 Senior Poster
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int x)
{
	if( x == 1 )
		return false;
	if( x % 2 == 0 && x != 2 )
		return false;
	if( x % 3 == 0 && x != 3 )
		return false;
	if( x % 5 == 0 && x != 5 )
		return false;
	if( x % 7 == 0 && x != 7 )
		return false;
	return true;
}

bool is_prime(int i)
{
	if(i < 2) return false;

	if(i == 2) return true;


	float half = ceil( sqrt((float(i))) ) + 1;

	for(int j = 2; j < half; j++)
		if(i % j == 0) return false;

	return true;
}
int main()
{
	int i = 0;

	cout << boolalpha;

	while(true)
	{
		if(isPrime(i) != is_prime(i))
		{
			cout<<"When your function versus my simple brute force disagrees : \n\n";

			cout<<"Result :  from your function : "<<i<<" is prime = "<<isPrime(i)<<endl;
			cout<<"Result :  from my function   : "<<i<<" is prime = "<<is_prime(i)<<endl;
			cout<<"\nCheck what google says\n\n";
			cin.get();  
			break;
		}
		i++;
	}
	
	return 0;
}
mrnutty 761 Senior Poster

"if there is anything in my codes which need explanation, please do not hesitate to ask"
I don't mean I can't follow the code, I mean its not cleanly written.

And just when you thought there isn't another way :

#include<iostream>
#include<cmath>
#include<limits>

using namespace std;
 
typedef double data_type ;

data_type Approx(data_type num)
{
	int deg = 10;

	data_type cpy = num;

	while(cpy > 9) { cpy/=10; deg++; };

	data_type i = num / deg;	
	
	while(num < i*i) 		
		i-= unsigned long(1 + log(num));	

	if( i < 1) i = 0;	

	for( ; i <= num; i++)
	{
		//power of 2 ?
		if(i * i == num) 
			return i;
		//return closest int approxment
	  else if( i * i > num)
			return i - 1;
	}	
	
	return i-1;

}
inline data_type Avg(data_type X, data_type Y) {
	return (X+Y)/2.0; 
}
data_type SquareRootOf(data_type Num, unsigned int precision = 30)
{
	//check for default precision = 10;
	precision = precision < 10 ? 10 : precision;

	data_type X = data_type(Approx(Num));

	if(X*X == Num)
		return X;

	data_type average = 0;

	while(precision--)
	{		
		data_type Y = Num/X;
		average = Avg(Y,X);
		
		if(average * average == Num) 
			return average;					
		else X = average;		
	}

	 return average;
}
int main()
{ 							
	
	for(float i = 145; i < 164; i+=0.1)	
	{
		cout.width(10);
		cout<<"(cmath,Mines) square root of : "<<i <<" is = ";
		cout.width(10);
		cout<<sqrt(data_type(i))<<"\t"<<SquareRootOf(data_type(i))<<endl;
	}
	return 0;
}
mrnutty 761 Senior Poster

Fail.

mrnutty 761 Senior Poster

you have an infinite loop :

while (moreOrder) {
 
	}
mrnutty 761 Senior Poster

simplify.

1) Make a bool function that takes a int i as a parameter and checks if it is a prime or not.
2) inside your loop, check if i to MAX is a prime.

your function prototype might look like this :

bool isPrime(int num);

HINTS :
a) How do you when a number is a prime ?
- When it is only evenly divisible by itself an 1.
b) Use the mod operator.

mrnutty 761 Senior Poster

I like that comparison, younghc, even though your code is not easy
to follow. Its pretty neat.

mrnutty 761 Senior Poster
//Create a string and initialize it to some string literal

for i = 0 to i less than the string.size ; i++)
//use string.charAt(i) to print  + "\n";
mrnutty 761 Senior Poster

1) you could create a vector.
2) Initialize it with the array content
3) use std::sort on the vector
4) use std::unique on vector
5) Then print out the vector

mrnutty 761 Senior Poster
- error C2143: syntax error : missing ';' before '.'
- missing type specifier - int assumed. Note: C++ does not support default-int
- 'test_player' : redefinition; different basic types
mrnutty 761 Senior Poster

NO, it should be :

tempate<typename Process>
Dheap { //code };
mrnutty 761 Senior Poster

You can't do this :

int a;
cin >> a;
string str[a]; //error a is not const
mrnutty 761 Senior Poster

your haven't initialized the variable "a". And it has to be const, when using it to determine the size of an array.

const int A = 10;
string str[A]; //good
int b = 3;
string str[b]; //error
mrnutty 761 Senior Poster

There is also conversion Function :

#include<iostream>
#include<cstring>

using namespace std;
 
class Letters
{
private:
	char str[50];
public:
	Letters()  { str[0] = '\0';}
	Letters(const char * p)  { strcpy(str,p);  }

	operator const char *() { return str; } //conversion function
};
int main()
{ 		
		Letters str("hello world");

		cout<<str;
}

Of course there are some subtle issues with that class, but we
shall not discuss it.

mrnutty 761 Senior Poster

First seed your rand function.

srand(time(0));

The this code :

for (int toss = 0; toss < coinToss; toss++)
    {
	    flip();
        if (toss == 1)
 
			heads++;
 
		else
 
			tails++;
 
     }

is wrong.

You need to assign the value return to a variable and then use it to compare.

for(int i = 0; i < 100; i++)
{
    int side = flip();
   if(side == 0) tails++;
   else heads++;
}
mrnutty 761 Senior Poster

There is always brute force :

float SquareRootOf(int num)
{
	int i = 0;
	//Check for perfect square root
	for(i = 0; ; i++)
	{
		if(i * i > num) break;
		else if(i * i == num) return float(i);
	}

	i-=2;
	float j = i;
	float precision = 0.00001f;
	while(j * j < num - precision )
		j+=precision;
	
	return j;
}
mrnutty 761 Senior Poster

I cant take const out. The teacher wants us to us his function and develop our code around it.

Well there is const_cast but generally, you shouldn't have to do this.

mrnutty 761 Senior Poster

In my school :

Software Engr : 100% deals with software
Computer Science : 70% Software, 30% hardware
Computer Engr : 50-50% Software to hardware.

mrnutty 761 Senior Poster

it didn't work when first input was a negative number then the next
input was the last number in the solution grid.

mrnutty 761 Senior Poster

"None of the solutions can match C++'s sqrt() function."

Well the solution I provided was derived from sqrt function, thus it
matches the exact output( if thats what you mean by "match").

I wonder if creating your own powerFunction counts as cheating to the
OP, since its not from stl.

Also the solution :

x = e ^ (ln(a)/2)  //same as sqrt(a);

could also be edited so it wont use the power function. Specifically , one can use taylor series of that expression
to create one's own iterative process.

Since :

e^x = SIGMA x^n/n! = 1 + x + x*x/2! + x*x*x/3! + x*x*x*x / 4! .......

one can use this process to determine the sqrt (a), where x = ln(a)/2

And this technically does not use pow or the sqrt function.

mrnutty 761 Senior Poster

1) Dont use system's command

2) To answer your question something like this : ?

string command = "color ";
string input = "";
cin >> input;
command += input;
system(command.c_str());
mrnutty 761 Senior Poster

This would also work with recursion :

void Pattern(int Row, int Left = 0)
{
	int Right = Row - Left - 1;

	const static int Mid = (Right + Left) / 2;

	if(Left > Right ) return;

	for(int i = 0; i < Row; i++)
	{
		if(i == Left) 
			cout<<"^"<<" ";
		else if(i == Mid)
			cout<<"^"<<" ";
		else if(i == Right)
			cout<<"^"<<" ";
		else cout<<"*"<<" ";
	}

	cout<<endl;;

	Pattern(Row,Left+1);
}
mrnutty 761 Senior Poster

Too time consuming. I would rather not do it at all then

And about the code snippet, if I create an instance of Mother,
and call HandleMessage<10> it would print "It works!\n".

But if I call it with any other value it would do nothing,
the reason I am not doing this, is that I don't know the values at compile time.

Care to give a little more background?

mrnutty 761 Senior Poster

first this is wrong :

for (int i=0; i<=arrSize; i++)  //it should be   i < arrSize
        myArr[i]=rand();      //creating array with random numbers

The same goes for sorting and displaying numbers.

mrnutty 761 Senior Poster

the cctype header has a function called isdigits(...). You can use that
to validate whether a string contains integer. There are also isspace(..)
among other things in that library. Check out the library , here
Here is an example :

#include<iostream>
#include<cctype>

using namespace std;

int main()
{
	string phoneNumber = "777777777";

	bool pass = true;

	for(int i = 0; i < phoneNumber.size(); i++)
	{
		if( isdigit(phoneNumber[i]) )
			pass = true;
		else
		{
			pass = false;
			break;
		}
	}
	
}
mrnutty 761 Senior Poster

Here is your code indented with code tags.

One problem with your function is that you never declared s1 and s2.

Below code fixes that :

#include <iostream>
using namespace std;

void drawShape(int nrP)
{
	int s1 = 0,s2 = 0;  //(NEW)

	for (int i = 1; i <= nrP; i++)
	{
		s1 = i - 1;
		s2 = (2 * nrP - 2 * i - 1); 
	
		for (int j = 1; j <= s1; j++)
			cout << '^';
		
		cout << '#';
	
		for (int j = 1; j <= s2; j++)
			cout << '^';
	
		cout << '#';

		for (int j = 1; j <= s1; j++)
			cout << '^';
	
		cout << endl;
	} 
}

int main()
{
       int nr = 0;

	cout << "Number of rows: ";
	cin >> nr;
	drawShape(nr);

return 0;
}
mrnutty 761 Senior Poster

but I have looked at this tutorial and it uses glut to make the window and print to it, how come?

Well it can do some printing stuff too, but its primary task is to create
the window and get inputs. You should use opengl to draw stuff. Of
course there are some draw stuff that makes your life easier, which
glut has, like drawing text or a sphere, among other things.

MattyRobot commented: he helps me time and time again +1
mrnutty 761 Senior Poster

I am not saying its faster than sqrt, but it calculates it without using sqrt.

sqrt(a) = x

x^2 = a

ln(x^2) = ln(a);

2ln(x) = ln(a)

ln(x) = ln(a) / 2

x = e ^ (ln(a)/2)  //same as sqrt(a);

//you can decompose it back to sqrt like so
x = (e^ln(a))^1/2
x = a ^ (1/2) = sqrt(a);
mrnutty 761 Senior Poster

portability :

"The actual type of size_t is platform-dependent; a common mistake is
to assume size_t is the same as unsigned int, which can lead to
programming errors, particularly as 64-bit architectures become more
prevalent"

KonkaNok commented: ..just what I was looking for. +1
mrnutty 761 Senior Poster

The unnamed fields may just be padding so that the structure's data is laid out correctly...Gerard4143

Yes, structure goes by units of 4.

mrnutty 761 Senior Poster
int cnt = 0;

for infinite loop
{
   //do stuff
   if(//do stuff is what i need) // then break;
  else cnt++;

  //if cnt is above the limit then break;
}
mrnutty 761 Senior Poster

Use the error handling that already built in, called stdexcept

mrnutty 761 Senior Poster

make projects.

guessing game, tic-tac-toe,...

mrnutty 761 Senior Poster

this is the answer about the count:

int counter (string s){
count=0;
for (int i=1;int i<s.length();i++)
count ++;
return count;
}

No offense but this was worthless.How about using the s.length().
It already is a function that returns the number of character. And your counter has bugs.

mrnutty 761 Senior Poster

.

mrnutty 761 Senior Poster

Thanks William, thanks for the suggestion. I understand how it can be done. But before I jump in and start implementing it myself I would like to make sure that I can not use the code that already exists. It seems reasonable to expect that such a code exists, though.

Maybe in 3rd party library. Use William suggestion. Also these function
might come in handy, they are in cctype header.
cctype

mrnutty 761 Senior Poster

can't I just use a string?

Yes you can :

#include <iostream>
#include <string>

using namespace std;

struct Student {
	string firstName;
	string lastName;
	bool canadianship;
	int grades[10];
};

Student newStudent[10];

void addFirstName() {
	string name;
	cout << "Student Name: ";
	cin >> name;
	newStudent[0].firstName = name;
}


int main() {
	addFirstName();
	cout << newStudent[0].firstName;	
	return 0;
}
mrnutty 761 Senior Poster

he should say 5, by the way.

mrnutty 761 Senior Poster

sizeof(array)/sizeof(double) ?

mrnutty 761 Senior Poster

Show more code.

mrnutty 761 Senior Poster

What would google do? It would oggle
the google baby.

mrnutty 761 Senior Poster

so if I was making a game I would use both then, open GL to draw to the screen and glut to handle input. thanks

Yes, you can use both together to make a game.

mrnutty 761 Senior Poster

Make a function that return a random int from 1-6;

then

player1 = randomDiceRoll();
player2 = randomeDiceRoll();
//and so on.

have a counter that counts points.
int playerPoints =0;
int compPoints = 0;

//use a while loop
while(true)
{
//roll dice
//check winner
//add points to winner
//check if game is over
if(playerPoints >= 2 ) { cout<<"Player won\n"; break; }
else if(compPoints >=2) { cout<<"comp won\n"; break; }
}

mrnutty 761 Senior Poster

arrays are pass by reference. They are pointers-to-ints. When you
pass an array to a function, and change its value you are changing the
original content and not its copy.

so this code :

int swap( int A[] )
{
	for( int i = 0; i < 10; i++ )
	{
		int temp = A[i];
		int ran = random(10);
		A[i] = A[ran];
		A[ran] = temp;		
	}
	return A[10];
}

You are changing the array original content. What you are returning is
junk since your array ranges from 0-9. And even if it wasn't junk you
would not be returning the whole array, just 1 element.

mrnutty 761 Senior Poster

arrays are pass by reference. They are pointers-to-ints. When you
pass an array to a function, and change its value you are changing the
original content and not its copy.

so this code :

int swap( int A[] )
{
	for( int i = 0; i < 10; i++ )
	{
		int temp = A[i];
		int ran = random(10);
		A[i] = A[ran];
		A[ran] = temp;		
	}
	return A[10];
}

You are changing the array original content. What you are returning is
junk since your array ranges from 0-9. And even if it wasn't junk you
would not be returning the whole array, just 1 element.

mrnutty 761 Senior Poster

opengl is a graphics library while glut is not.
You use glut with opengl to handle graphics. glut handles with mostly
the input. It could create the graphics window, handle key input and some other fancy stuff. You use opengl to draw primitives onto the window
that glut creates.

mrnutty 761 Senior Poster

Its because of logic :

for (int i=0; i<list.size(); i++) { ...}

Lets make a table :

i   list.size()   list.top   i < list.size()
----------------------------------------------
0     3          2323            true
1     2          10                true
1     1          20                false

So what a for loop does is this :

for(  statement1;  bool statement ; increment statement; )  { loop body}

First statement1 gets executed
Then bool statement gets executed
Then loop body gets executed
Then increment statement gets executed

Following this that the last element in the table does
not get executed.

I am not sure why you are using list anyways. Use vector.

mrnutty 761 Senior Poster

goggle Separating axis theorem.

jasimp commented: Love your avatar pic. Nice suggestion too :) +11
mrnutty 761 Senior Poster

call your stack something like Stack. Because the standard c++ has
a stack class.

mrnutty 761 Senior Poster

I can't see the image?