Project Euler #52: Permuted multiples (C++)

Question
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

Answer : 142857

Hacker Rank Problem

Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int hasSameDigits (int num1, int num2) {
    int digits[10], i;
    for (i = 0; i < 10; i++)      
        digits[i] = 0;
    while (num1 != 0)
    {          
        digits[num1%10]++;        
        num1 /= 10;               
    }
    while(num2 != 0) 
    {           
        digits[num2%10]--;
        num2 /= 10;
    }
    for (i = 0; i < 10; i++)
        if (digits[i] != 0)       
            return 0;
    return 1;                  
}

int main() {
    int n, k, flag;
    cin>>n>>k;
    for(int i = 1; i<=n; i++)
    {
        flag = 0;
        for(int j=2; j<=k; j++)
        {
            if(!hasSameDigits(i, j*i))
                break;
            else
                flag++;
        }
        if(flag == k-1)
        {
            for(int z = 1; z<=k; z++)
            {
               cout<<i*z<<" ";
            }
        cout<<endl;
        }
    }
    return 0;
}

Comments

Popular Posts