2013年4月4日 星期四

[C]book page 203 problem 2&4 solution

book page 203 problem 2 solution

float i=1,pow,sum;
printf(" X\t X*X\t X+X\n");
while(i <= 10)
{
	pow=i*i;
	sum=i+i;
	printf("%3.1f\t%5.2f\t%4.2f\n",i,pow,sum);
	i+=0.5;
}

book page 203 problem 4 solution

Method 1

int n,i=2;
bool result=true;
printf("Please enter integer N >");
scanf("%d",&n);
if(n%2 == 0)
{
	result=false;
}
else
{
	while(i < n)
	{
		if(n%i == 0)
		{
			result=false;
			break;
		}
		i++;
	}
}
if(result)
	printf("The number you enter,%d,is prime number\n",n);
else
	printf("The number you enter,%d,is NOT prime number\n",n);

Method 2

int n,i=2;
printf("Please enter integer N >");
scanf("%d",&n);
while(i < n)
{
	if(n%i == 0)
	{
		printf("The number you enter,%d,is NOT prime number\n",n);
		break;
	}
	i++;
}
if(i == n)
	printf("The number you enter,%d,is prime number\n",n);

Method 3

int n,i=2;
printf("Please enter integer N >");
scanf("%d",&n);
while(n%i != 0)
{
	i++;
}
if(i < n)
	printf("The number you enter,%d,is NOT prime number\n",n);
if(i == n)
	printf("The number you enter,%d,is prime number\n",n);

沒有留言:

張貼留言