aboutsummaryrefslogtreecommitdiffstats
path: root/tests/GeneratorTestApp/Prime.cs
blob: 16438db42b6ba14eca795636d3618114a1d58a95 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/***************************************************************************************************
 Copyright (C) 2025 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System.ComponentModel;
using Qt.DotNet.Utils;

namespace GeneratorTestApp
{
    public class Prime : INotifyPropertyChanged
    {
        public int Index
        {
            get => lazy.Get(() => Index, () => 0);
            set
            {
                lazy.Set(() => Index, value);
                Value = NthPrime(value + 1);
            }
        }

        public int this[int idx] { get => NthPrime(idx); set { } }
        public int this[string idx] { get => NthPrime(int.Parse(idx)); set { } }

        public int Value
        {
            get => lazy.Get(() => Value, () => 2);
            set => lazy.Set(() => Value, value);
        }

        public event PropertyChangedEventHandler PropertyChanged
        {
            add { lazy.PropertyChanged += value; }
            remove { lazy.PropertyChanged -= value; }
        }

        private LazyFactory lazy = new();

        private static int NthPrime(int n)
        {
            int x = 2;
            while (n > 0) {
                if (IsPrime(x))
                    --n;
                ++x;
            }
            return x - 1;
        }

        private static bool IsPrime(int x)
        {
            if (x <= 1)
                return false;
            if (x == 2 || x == 3)
                return true;
            if (x % 2 == 0 || x % 3 == 0)
                return false;
            for (int i = 5; i * i <= x; i += 6)
                if (x % i == 0 || x % (i + 2) == 0)
                    return false;
            return true;
        }
    }
}