You are hereProgramming Problems / 2011 Programming Solutions2

2011 Programming Solutions2


By gconway - Posted on 27 April 2012

WordTurn

#include <iostream>
#include <string.h>

using namespace std;

const int MAXLENGTH = 15;

main()
{
        char word[MAXLENGTH+1], rotated[MAXLENGTH+1];
        int n;

        cin >> word;
        cin >> n;

        int len = strlen(word);
        for(int i = 0; i < len; i++)
                rotated[(i + n) % len] = word[i];

        // Terminate the word
        rotated[len] = 0;

        cout << rotated << endl;

        return 0;
}

 

Prime Numbers

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <math.h>

using namespace std;

const int FALSE = 0;
const int TRUE = !FALSE;

int isPrime(long num)
{
        if (num < 2)
                return FALSE;
        int SqrtNum = sqrt(num);
        for (int i = 2; i <= SqrtNum; i++)
                if (num % i == 0)
                       return FALSE;

        return TRUE;
}

main()
{
   int low, high;
        cin >> low >> high;

        int count = 0;
        for(int i = low; i <= high; i++)
           if(isPrime(i))
           {
              //cout << i << " ";
              count++;
           }

   cout << count << endl;
        return 0;
}

 

Prime Substrings

 

#include <iostream>

#include <string.h>
#include <stdlib.h>
#include <math.h>

using namespace std;

const int FALSE = 0;
const int TRUE = !FALSE;

const int MAXDIGITS = 10;
char number[MAXDIGITS + 1];     // 1 for a zero

long GetSub(int start, int len)
{
        long sub = 0;
        int end = len + start;

        for(int i = start; i < end; i++)
                sub = sub * 10 + number[i];

        return sub;
}

int IsPrime(long num)
{
        if (num < 2)
                return FALSE;

        int SqrtNum = sqrt(num);
        for (int i = 2; i <= SqrtNum; i++)
                if (num % i == 0)
                        return FALSE;

        return TRUE;
}
main()
{
        cin >> number;

        int NumDigits = strlen(number);

        // UnASCII number
        for (int i = 0; i < NumDigits; i++)
                number[i] -= '0';

        // Work down thru all lengths (all possible subsequence lengths)
        for (int len = NumDigits; len > 0; len--)
                {
                long BestPrime = 0;
                for (int start = 0; start <= NumDigits - len; start++)
                        {
                        long sub = GetSub(start, len);
                        if (IsPrime(sub))
                                if (sub > BestPrime)
                                        BestPrime = sub;
                        }
                if (BestPrime > 0)
                        {
                        // Found the largest prime,
                        cout << BestPrime << endl;
                        exit(0);
                        }
                }

        cout << "No Primes\n";
        return 0;
}