Author Archives: MantasCode

C# Project Euler Problem 954 Heptaphobia

A positive integer is called heptaphobic if it is not divisible by seven and no number divisible by seven can be produced by swapping two of its digits. Note that leading zeros are not allowed before or after the swap.

For example, 17 and 1305 are heptaphobic, but 14 and 132 are not because 14 and 231 are divisible by seven. Let C(N) count heptaphobic numbers smaller than N. You are given C(100) = 74 and C(10^4) = 3737.

Find C(10^13)

https://projecteuler.net/problem=954

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Heptaphobic_Super_Optimal
{
    internal class Program
    {
        static void Main(string[] args)
        {
 
            DateTime s_time = DateTime.Now;
 
            long max = 100;   // example upper bound
            long count = CountHeptaphobic(max);
 
 
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(max + " Heptaphobic count: " + count);
            Console.WriteLine();
            Console.WriteLine();
 
 
 
            Console.WriteLine();
            Console.WriteLine();
            DateTime e_time = DateTime.Now;
            Console.WriteLine("Duration   " + (e_time - s_time).TotalMinutes + " minutes");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
 
        }
 
 
        static long CountHeptaphobic(long max)
        {
            const int MaxDigits = 18;
            long[,] pow10Mod7 = new long[MaxDigits + 1, MaxDigits];
            for (int len = 1; len <= MaxDigits; len++)
            {
                pow10Mod7[len, len - 1] = 1;
                for (int i = len - 2; i >= 0; i--)
                    pow10Mod7[len, i] = (pow10Mod7[len, i + 1] * 10) % 7;
            }
 
            object lockObj = new object();
            long total = 0;
 
            Parallel.For(1L, max, () => 0L, (n, state, local) =>
            {
                if (IsHeptaphobicNumeric(n, pow10Mod7))
                    local++;
                return local;
            },
            local => { lock (lockObj) total += local; });
 
            return total;
        }
 
        static bool IsHeptaphobicNumeric(long num, long[,] pow10Mod7)
        {
            int[] digits = new int[18];
            int len = 0;
            long tmp = num;
            while (tmp > 0)
            {
                digits[len++] = (int)(tmp % 10);
                tmp /= 10;
            }
            Array.Reverse(digits, 0, len);
 
            long mod7 = 0;
            for (int i = 0; i < len; i++)
                mod7 = (mod7 + digits[i] * pow10Mod7[len, i]) % 7;
 
            if (mod7 == 0)
                return false;
 
            for (int i = 0; i < len; i++)
            {
                for (int j = i + 1; j < len; j++)
                {
                    if (i == 0 && digits[j] == 0)
                        continue;
 
                    long delta = ((digits[i] - digits[j]) * (pow10Mod7[len, j] - pow10Mod7[len, i])) % 7;
                    long newMod = (mod7 + delta + 7) % 7;
                    if (newMod == 0)
                        return false;
                }
            }
 
            return true;
        }
 
 
    }
}

Using Grok API (xAI) with Live Web Search to Perform Skip Trace Automation in C# .NET

Simple C# Console Application demonstrates how to programmatically utilize the Grok API with Live Web Search.

Below I am structuring a question pattern into a JSON payload. Then using an HTTP Client to submit the payload to Grok’s endpoint https://api.x.ai/v1/responses. Result content is then parsed, sanitized, and displayed.

Model used grok-4-1-fast-reasoning
Temperature used 0.0

This example:
Uses HttpClient
Sends a Grok chat request
Enables web search
Prints the final response

Full working C# Console App example that calls Grok (xAI) API and sends a JSON payload enabling web search. Must replace (Your-Grok-API-Key), with your own key.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using Formatting = Newtonsoft.Json.Formatting;
 
namespace Grok_API_WithWebSearch_Skip_Tracing
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            /////////////////////////////////////////////////////////////////////
            //SKIP Trace automation example using GROK API with Live Web Search//
            //Model: grok-4-1-fast-reasoning/////////////////////////////////////
            //This program uses Nuget Package: Newtonsoft.Json///////////////////
            /////////////////////////////////////////////////////////////////////
 
            string apiKey = "(Your-Grok-API-Key)"; // <-- Replace this with your key
            string endpoint = "https://api.x.ai/v1/responses";
 
//Structure your question//
//"What is the best Phone Number for [Business Name] in [City], [State], [Zip]?  Please respond with Phone Number only or 'Not found' if unavailable."//
            string question = "What is the best Phone Number for Boathouse in Chattanooga, TN?  Please respond with Phone Number only or 'Not found' if unavailable.";
 
            Console.WriteLine("Asking Grok,");
            Console.WriteLine(question);
            Console.WriteLine();
 
            //Create JSON payload//
            var payload = new
            {
                model = "grok-4-1-fast-reasoning",
                input = question,
                tools = new object[]
                {
                new { type = "web_search" }
                },
                tool_choice = "auto",
                temperature = 0.0
            };
            string jsonPayload = JsonConvert.SerializeObject(payload, Formatting.Indented);
 
            //Start Timer//
            DateTime start_time = DateTime.Now;
 
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(endpoint, content);
                string result = await response.Content.ReadAsStringAsync();
 
                try
                {
                    JObject parsed = JObject.Parse(result);
                    var outputArray = parsed["output"] as JArray;
                    string assistantText = null;
                    foreach (var item in outputArray)
                    {
                        var contentArray = item["content"] as JArray;
                        if (contentArray != null)
                        {
                            foreach (var block in contentArray)
                            {
                                if ((string)block["type"] == "output_text")
                                {
                                    assistantText = (string)block["text"];
                                    break;
                                }
                            }
                        }
                        if (assistantText != null) break;
                    }
                    if (assistantText != null)
                    {
                        // Regex pattern for phone number (simple US-style)
                        string phonePattern = @"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}";
 
                        // Extract Phone Number//
                        Match phoneMatch = Regex.Match(assistantText, phonePattern);
                        string phoneNumber = phoneMatch.Success ? phoneMatch.Value : "Not found";
 
                        //Output Phone Number//
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Grok Response,");
                        Console.WriteLine(NormalizePhoneNumber(phoneNumber));
                        Console.ResetColor();
                        Console.WriteLine();
 
                        //Stop Timer//
                        DateTime end_time = DateTime.Now;
                        Console.WriteLine("Time elapsed : " 
+ (end_time - start_time).TotalSeconds.ToString("F2") + " seconds");
                        Console.WriteLine();
                    }
                }
                catch (Exception ex)
                {
                    Console.ResetColor();
                }
            }
        }
 
        //Mehtod for formatting phone number structure variance//
        static string NormalizePhoneNumber(string input)
        {
            //Remove all non-digit characters//
            string digits = Regex.Replace(input, @"\D", "");
            //Ensure it has 10 digits//
            if (digits.Length != 10)
                throw new ArgumentException("Phone number must have 10 digits after removing formatting.");
            //Format consistently: (###) ###-####//
            return $"({digits.Substring(0, 3)}) {digits.Substring(3, 3)}-{digits.Substring(6, 4)}";
        }
    }
}

Twitter and Tesla Employee Political Candidate Donations

Which political candidates received the most amount of money from Twitter and Tesla employees?

A look into Twitter and Tesla employee political candidate contributions. The data comes from Federal Election Commission and covers election cycles 2016, 2018, 2020, and 2022. Click on Tree Maps below for full size.
Box Size = Money
Color = Party (Democrat vs Republican)

Denver Cocaine 2017 – 2022

A look into city and county of Denver’s cocaine criminal offenses. The data is based on the National Incident Based Reporting System (NIBRS). The data is collected by The Denver Police Department, and spans from January 2017 through August 2022. The data source can be accessed at www.denvergov.org. Click on images below for full resolution.

Offense Category of drug-alcohol

Offense Type containing cocaine. (drug-cocaine-possess and drug-cocaine-sell)

Offense Type drug-cocaine-possess vs. drug-cocaine-sell