Need help :: Getting WA :: Quiz 1

12 views
Skip to first unread message

Menon

unread,
Dec 16, 2014, 5:56:15 AM12/16/14
to akab...@googlegroups.com
#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

int isPrime(int n);
int getMod(string num);

int main()
{
    string num;
    int mod;

    while(cin >> num)
    {
        mod = getMod(num);

        if(mod == 0 || isPrime(mod))
            cout << "Sauron\'s evil spirit!" << endl;
        else
            cout << "You passed the test." << endl;
    }

    return 0;
}
int getMod(string num)
{
    int n = 0;
    for(int i = 0; num[i]; i++)
    {
        n = n * 10 + num[i] - '0';
        n = n % 13;
    }

    return n;
}
int isPrime(int n)
{
    if(n <= 1)
        return 0;
    if(n == 2)
        return 1;
    if(n % 2 == 0)
        return 0;
    for(int i = 3; i * i <= n; i += 2)
    {
        if(i % 2 == 0)
            return 0;
    }

    return 1;
}



Md. Abul Kalam Azad

unread,
Dec 16, 2014, 3:42:50 PM12/16/14
to akab...@googlegroups.com
Can anyone hint him to find his bug?

shahidul.cse.brur

unread,
Dec 18, 2014, 11:10:11 AM12/18/14
to akab...@googlegroups.com
Menon, your prime checking is wrong ! why you are using



if(i % 2 == 0)
        return 0;


use
if(n % i == 0)
            return 0;

 

Menon

unread,
Jan 3, 2015, 5:39:56 AM1/3/15
to akab...@googlegroups.com
if a number is divided by 2 than this number is not a prime number.
so why if( n % 2 == 0 )  this checking is wrong.

shahidul.cse.brur

unread,
Jan 3, 2015, 8:59:50 AM1/3/15
to akab...@googlegroups.com
By using -

for(int i = 3; i * i <= n; i += 2)
    {
        if(i % 2 == 0)
            return 0;
    }

you are always checking if i is divided by 2 or not.
Here is two misteke:
1) for loop used here for checking if there any number i by which n%i==0, if there is any value of i, then n is not prime.
    So, i is divisor here, not divined.

2) You always checking if divisible by 2. This is wrong. You should use every number <= sqrt(n) to check whether it can divide n or not.
    so, here divisor should be i not 2.
 Your function is to check whether n is prime or not. So check n%i==0 or not. why you are checking if i%2==0 or not??

For any further query keep posting.

Menon

unread,
Jan 3, 2015, 9:49:09 AM1/3/15
to akab...@googlegroups.com
I have got my mistake that was in isPrime ( ) function for loop .accepted code is 
 if(n % i == 0)
            return 0;

instate of 
 if(i % 2 == 0)
            return 0;


tnx Md.Shahidul Islam. 
Reply all
Reply to author
Forward
0 new messages