Square digit chains


A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example, 44 → 32 → 13 → 10 → 1 → 185 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?


public static int count = 0;

        static void Main(string[] args)
        {
            for(double i = 1; i <= 10000000; i++)
            {
                Power(i);
            }
            Console.WriteLine(count);
            Console.ReadLine();
        }

        public static void Power(double n)
        {
            string s = n.ToString();
            double power = 0;

            foreach(char c in s)
            {
                int eachchar = (int)Char.GetNumericValue(c);
                power += Math.Pow(eachchar, 2);
            }

            if (power == 1) { return; }
            else if (power == 89) { count++; }
            else { Power(power); }
        }

Factorials!!! (1083) C#, C++


Today’s problem can be read here.
Here’s my code, it’s easy to read and understand, but yes, I admit it, it looks HORRIBLE, I could pull it much much much much much more, it’s gross and nasty (but functional).


using System;

namespace _1083
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ');

            int n = Int32.Parse(s[0]);
            int k = s[1].Length;

            int ans = n;
            if(n == 1)
            {
                ans = 1;
            }
            else if(k >= n)
            {
                ans = n;
            }
            else if(n % k != 0)
            {
                for(int i = 1; i < 10000; i++)
                {
                    ans = ans * (n - k * i);
                    if ((n - k * i) == (n % k)) { break; }
                }
            }
            else
            {
                for(int i = 1; i < 10000; i++)
                {
                    ans = ans * (n - k * i);
                    if ((n - k * i) == k) { break; }
                }
            }

            Console.WriteLine(ans);
        }
    }
}

I found this solution, it works perfectly well, and it’s beautifully written:


#include <iostream>
#include <string>

using namespace std;
unsigned long long res = 1;
int n, len;
string a;

int main()
{
    cin>>n;
    cin>>a;
    len = a.size();
    for(int i = n; i > 0; i -= len) res *= i;
    cout << res << endl;
    return 0;
}

I think that we could actually change the unsigned long long for an int.
Here’s a cool video about factorials:


And a cool application (yes, it has to do with combinatorics): Binomial Coefficient.

Amicable numbers (Problem 21) C#

This problem and message was taken from Project Euler

NOTICE

On Sunday 15 June 2014 it was discovered that Project Euler had been hacked and a decision was made to take the website offline. Project Euler has existed since 2001 and after thirteen years of it being carefully nurtured to become what it has become today we hope you understand that this decision was not made lightly. No one feels this sadness more than the team.

As the strength and priority of Project Euler is the rich and challenging problem set it provides then we are pleased to be able to allow the problems to remain accessible. However, please note that full functionality of the website, including the ability to check answers, register, and login to existing accounts, remains disabled. Over time certain features may be reinstated, but currently there is no definite time frame which can be stated. In addition no new problems are likely to appear until the website is back up and running again.

Amicable numbers:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.


using System;
using System.Collections.Generic;
using System.Linq;

namespace Problem_21
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<int>> x = new List<List<int>>();
            for(int a = 1; a < 10000; a++)
            {
                List<int> y = new List<int>();
                for(int b = 1; b <= a/2; b++)
                {
                    if (a % b == 0) { y.Add(b); }
                }
                x.Add(y);
            }

            int ans = 0;
            int k = 0;
            for(int h = 0; h <= 9998; h++)
            {
                int i = x[h].Sum();
                int j = (h + 1);
                if ((i >= 1) & (i <= 9998))
                {
                    k = x[i - 1].Sum();
                }
                else
                {
                    continue;
                }

                if ((k == j) && (j != i))
                {
                    ans += j;
                }
                k = 0;
            }

            Console.WriteLine(ans);
            // ans = 31626, takes less than a second to run.
            Console.ReadLine();
        }
    }
}

I think that the trickiest thing in the ode is the multidimensional List, included in System.Collections.Generic, here’s what MSDN says about it:
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.
It’s much more powerful than using arrays, but it also takes more space in memory, however you can use very powerful algorithms to sort, sum, convert, etc. Here’s an example of the multidimensional List, taken from StackOverflow:


        List<List> table = new List<List>();
        List row = new List();
        row.Add(21);
        row.Add(22);
        row.Add(23);
        row.Add(33); // and so on
        table.Add(row);

        row = new List();
        row.Add(1001);
        row.Add(1002);
        table.Add(row);

        MessageBox.Show(table[0][3].ToString()); // Shows 33
        MessageBox.Show(table[1][0].ToString()); // Shows 1001

Easy and funny, hi5!

First Timus Problem (1000) C, C++, C#, Python

I just noticed that I haven’t put the solution to the first problem anywhere in here, and just for the record…

Problem: Make a program that takes as input integers ‘a’ and ‘b’. The output must be a+b.
C:


#include <stdio.h>
int main()
{
   int a, b;
   scanf("%d%d", &a, &b);
   printf("%d\n", a + b);
   return 0;
}

C++:


#include <iostream>

using namespace std;

int main()
{
       int a,b;
       cin >> a >> b;
       cout << a+b;
       return 0;
}

or…


#include <iostream>

int main()
{
       int a,b;
       std::cin >> a >> b;
       std::cout << a+b << std::endl;
       return 0;
}

C#:


using System;

public class Sum
{
    private static void Main()
    {
        string[] ans = Console.ReadLine().Split(' ');
        Console.WriteLine(int.Parse(ans[0]) + int.Parse(ans[1]));
    }
}

Python:


print(sum(int(a) for a in input().split(' ')))

SMS-spam (1567) C++, C#


Petr, a student, decided to start his own business. He offers SMS advertising services to the business owners renting offices in the newly built “Prisma” tower. If an office owner wants to use the service, he devises a slogan and Petr texts it from his personal phone to thousands of Ekaterinburg citizens (he already bought the pirated list of mobile phone numbers). The cost of each slogan sent is a sum of costs of each character typed. Cost of an individual character is determined according to a very simple scheme: each tap at the phone’s keyboard costs 1 rouble.
Petr’s phone doesn’t support sophisticated text input technologies, such as T9, and only the english alphabet can be used.

1 a b c 2 d e f 3 g h i
4 j k l 5 m n o 6 p q r
7 s t u 8 v w x 9 y z
0 . , ! # _

The “_” character in the table denotes whitespace. If you want to, for example, type “a”, you need to press the “1” button once. To type “k”, you press “4” twice. To type “!”, press “0” three times.
Petr has to apply this simple algorithm to calculate the cost of every slogan he sends. However, Petr is a very busy man (and, as a matter of fact, doesn’t bother to learn arithmetics, because he’s a Philosophy student). You just have to help Petr, you are his best friend after all.

Input: The single line of input contains the slogan. Slogan consists of words, spaces, commas, full stops and exclamation marks. All the words consist of lowercase english letters. Slogan can’t be longer than 1000 characters.

Output: Output a single number representing the cost of the given slogan, according to Petr’s pricing.

Sample:

Input Output
pokupaite gvozdi tolko v kompanii gvozdederov i tovarischi! 114

The C++ code:


#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    getline(cin, str);
    int strSize = str.size();

    int ans = 0;
    for(int i = 0; i < strSize; i++)
    {
        if(str[i] == 97 || str[i] == 100 || str[i] == 103 || str[i] == 106 || str[i] == 109 || str[i] == 112 ||
           str[i] == 115 || str[i] == 118 || str[i] == 121 || str[i] == 32 || str[i] == 46)
        {
            ans+=1;
        }
        else if(str[i] == 98 || str[i] == 101 || str[i] == 104 || str[i] == 107 || str[i] == 110 ||
                 str[i] == 113 || str[i] == 116 || str[i] == 119 || str[i] == 122 ||  str[i] == 44)
        {
            ans+=2;
        }
        else
        {
            ans+=3;
        }
    }

    cout << ans;
    return 0;
}

Notice that this time, instead of using Console In (cin >> x), I’m using getline(cin, x), the reason is that >> operator is the defined as C’s scanf %s: «Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.» Since that would be a problem because of the spaces, I had to use getline from the <string> library: «Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ‘\n’, for (2)).». It takes two parameters, the first one is the object from which characters are extracted (istream) and the second one the object where the extracted line is stored (string): getline(istream, string).
I also used std::string::size, which simply returns the length of a string in terms of number of characters.
And here’s the much more simpler C# code:

using System;

namespace _1567
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            char[] arr;

            int ans = 0;
            arr = str.ToCharArray(0, str.Length);
            foreach(char c in arr)
            {
                if (c == 97 || c == 100 || c == 103 || c==106 || c==109 || c==112 || c==115 || c==118 || c==121 
                || c==32 || c==46) { ans += 1; }
                else if(c==98 || c==101 || c==104 || c==107 || c==110 || c==113 || c==116 || c==119 || c==122 || c==44)
                { ans += 2; }
                else { ans += 3; }
            }
            Console.WriteLine(ans);
            Console.ReadLine();
        }
    }
}

I used a method from String which is String.ToCharArray, it takes two parameters, the starting position of the string and the length we are taking string.ToCharArray(start, length). For example:


string str = "Hello world!";
char[] arr;
arr = str.ToCharArray(6,5);

The foreach statement is very easy to comprehend, however, here’s what MSDN says:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.

At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.

Mathematicians and berries (2001) C++, C#

One day, two mathematicians were walking in the forest and picking berries. They’d been walking for two hours, and then they stopped and decided to see who’s got more berries. They took out the scales (can you imagine a mathematician going to the forest without any scales?) and they weighed their baskets with berries. They wrote the resulting numbers a1 and b1 down on a piece of paper. Then the second mathematician put all his berries to the first one’s basket (so that his basket became completely empty) and they weighed their baskets again and they received numbers a2 and b2, correspondingly. At last, the first mathematician put all the berries to the second one’s basket (so that his basket became completely empty); they weighed the baskets and got numbers a3 and b3, correspondingly. This data was enough to find the winner and the happy mathematicians moved on. Your task is to calculate the mass of the berries in each mathematician’s basket by the start of the competition.

Input: The input data consists of three lines. The i’th line (1 ≤ i ≤ 3) contains integers ai and bi (0 ≤ ai, bi ≤ 10 000).

Output: Output the weight of berries in the basket of the first and the second mathematician correspondingly.

Sample:

Input Output
1 2 1 1
2 1
0 3

This problem is as easy as (a1 – a3) (b1 – b2), the code is here:

C++


#include <iostream>
using namespace std;

int main()
{
    int a1, a2, a3, b1, b2, b3;
    cin >> a1 >> b1;
    cin >> a2 >> b2;
    cin >> a3 >> b3;

    cout << a1 - a3 << " " << b1 - b2;

    return 0;
}

C#


using System;

namespace _2001
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s1 = (Console.ReadLine()).Split(' ');
            string[] s2 = (Console.ReadLine()).Split(' ');
            string[] s3 = (Console.ReadLine()).Split(' ');
            int a1 = Int32.Parse(s1[0]);
            int a3 = Int32.Parse(s3[0]);
            int b1 = Int32.Parse(s1[1]);
            int b2 = Int32.Parse(s2[1]);

            Console.WriteLine((a1 - a3) + " " + (b1 - b2));
        }
    }
}

Four Imps (1924) C++, C#

The world is in danger. One famous swindler passed away recently (by the way, nobody knows his real name, so let’s call him Ostap). Having got to the hell he decided to make a deal with the Devil. More precisely, it was, actually, not a deal but a stake in a totalizator. The rules of the game are quite simple. Several imps divide into two teams — “black” and “grimy”. Then they go to the game field. Numbers from 1 to n are written on the field, and the teams do their turns one after another by putting down with black ink signs of + and − between the numbers. When there is no two adjacent numbers without sign between them left, players calculate the result of obtained expression on the field. The goal of the “black” team is to make this result even, the goal of the “grimy” team is to make it odd. All four imps are experts in this game, therefore they always do optimal turns. “Black” team plays first.
The totalizator rules are the following: if Ostap guesses which team wins, he will get his life back. Otherwise, the Devil will get the power over the whole world. The stakes are high, so you have to help Ostap with determining the winner.

Input: The input is a single integer n (1 ≤ n ≤ 50).

Output: If “black” team wins output “black”, otherwise output “grimy”.

Sample:

Input Output
1 grimy
4 black

We can see that:

1 grimy
1+2=3 grimy
1+2+3=6 black
1+2+3+4=10 black

And yes, we are getting the triangular numbers, and yes, whenever the number is even the black imps will win, and whenever the number is odd the grimy imps will win.
Oh triangular numbers, how beautiful you are…

We have our Triangular number T(n) by adding all the natural numbers up to the nth term, for example T(3) would be 6 since 1+2+3=6. We can prove that our formula (N*(N+1))/2 will always give us a triangular number Tn using the Induction Axiom, introduced by Peano: we assume that if our formula holds for 1+2+3+…+n and it also for 1+2+3+…+n+(n+1) then it must be true to infinity.

And back to our problem, we can solve it by simply using our Tn formula to see if the number is even or odd.

C++:


#include <iostream>
using namespace std;

int main()
{
	int ans;
	cin >> ans;
	if (((ans * (ans + 1)) / 2) % 2 == 0) { cout << "black"; }
	else { cout << "grimy"; }
	return 0;
}

C#:


using System;

namespace _1924
{
   class Program
   {
       static void Main(string[] args)
       {
           int ans = Int32.Parse(Console.ReadLine());
           if(((ans * (ans + 1)) / 2) % 2 == 0) { Console.WriteLine("black"); }
           else { Console.WriteLine("grimy"); }
       }
    }
}

Recap 1, C#

I’ve solved my first 10 problems only with C#; and now I’m planning on solving the others either with C++, C# or both, but first I want to do a little recap of the things I’ve done so far (I’m planning on doing this every 10 problems).

Bubble sort: Compares two adjacent items in an array and swap them if they are in the wrong order, it keeps doing this until no swapping is needed. I don’t know why I can’t make WordPress to display my code properly, so I took this image from StackOverflow.

Ceiling and Floor methods: It takes a double value and returns the next closest upper/lower integer.


Math.Ceiling(myDoubleValue);
Math.Floor(myDoubleValue);

String.Split method: It creates an array with an element for every separator that is found in the original string.


string[] s = originalString.Split(separator);

Array.Sum method: This uses LINQ to sum all the elements in an array.


int sum = array.Sum();

Array.ForEach method: It performs the specified action on each element of the specified array.


Array.ForEach(myArray, whatIWantToDo);

Int32.Parse method: Last but not least, something very useful that I’ve been using again and again, it takes a string and tries to convert it to an integer value.


int myNewInt = Int32.Parse(string);

Chocolate 2 (1639) C#

This is another little gift/joke from the AC Timus. From now onwards I won’t write the problem unless it’s necessary or interesting.

The code:

using System;

namespace _1639
{
   class Program
   {
       static void Main(string[] args)
       {
           string[] s = (Console.ReadLine()).Split(' ');
           int m = Int32.Parse(s[0]);
           int n = Int32.Parse(s[1]);

           if((m*n)%2 == 0) { Console.WriteLine("[:=[first]");
           else { Console.WriteLine("[second]=:]");
        }
   }
}

The only interesting thing from this problem is the math... but it's pretty simple too; the nth time you break the chocolate in a half, you get n+1 pieces of chocolate, so the winner will be the one who has the chocolate on the (m*n)-1 turn. C'est tout!

Titan Ruins: Hidden Entrance (1910) C#

This one was very easy too, here’s the link to the problem: Timus

The code is very readable and easy to understand too:


using System;

namespace _1910
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
            string[] s = (Console.ReadLine()).Split(' ');
            int[] k = new int[s.Length];

            for(int h = 0; h < s.Length; h++)
            {
                k[h] = Int32.Parse(s[h]);
            }

            int place = 0;
            int sum = 0;
            for(int h = 0; h sum) { sum = (k[h] + k[h + 1] + k[h + 2]); place = h + 2; }

            }
            Console.WriteLine(sum + " " + place);
            Console.ReadLine();
        }
    }
}