Write your question here.
So i was doing the homework for my class, and I was stuck as always and asked my friend to help me with it. he wrote the code correctly...in stdio.h
I need it to be iostream, but I have no clue how to change it
Please help me
[code]
Put the code you need help with here.
#include<stdio.h>
#include<string.h>
#include<math.h>
bool isprime(int);
int countprime(int);
bool isprime(int n)
{
int i,j,k,f=0;
int d=sqrt(n);
for(i=2;i<=d;i++)
{
if(n%i==0)
{
f=1;
i=i+d;
}
}
if(f==1)
return false;
else
return true;
}
int countprime(int n)
{
int i,j,k,count=0;
for(i=2;i<=n;i++)
{
int f=0;
int d=sqrt(i);
for(j=2;j<=d;j++)
{
if(i%j==0)
{
f=1;
j=j+n;
}
}
if(f==0)
count++;
}
return count;
}
int main()
{
int i,j,n;
bool k;
printf("Enter an integer:\n");
scanf("%d",&n);
while(n>=0)
{
if(n>1)
{
k=isprime(n);
if(k)
printf("%d is a prime? true\n",n);
else
printf("%d is a prime? false\n",n);
j=countprime(n);
printf("Number of primes <= %d: %d\n",n,j);
}
else if(n==0)
{
printf("%d is a prime? false\n",n);
printf("Number of primes <= %d: %d\n",n,0);
}
else if(n==1)
{
printf("%d is a prime? false\n",n);
printf("Number of primes <= %d: %d\n",n,0);
}
printf("Enter another integer:\n");
scanf("%d",&n);
}
return 0;
}
%X is used to replace with a variable so printf(%d is a prime? false\n",n); would be equal to cout << n << " is a prime? false" << std::endl;
Anyways I would suggest writing it in your own version and not just converting it from c to c++. Another thing to mention is that those prime functions are very slow and do unnecessary checks. I would suggest using a sieve. One of the easiest to implement is the sieve of eratosthenes http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Basically %d means you are inputting into an integer variable and &n is the address of n. So you will want to do cin >> n; also you are reading into the variable n. It would be hard to read into a newline.
If your homework is on functions, loops, input, output then your teacher should have taught you how to use cout and cin.