ivandrofly

check binary divisibility

Mar 9th, 2021
494
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. namespace NumberDivisible
  2. {
  3.     using System;
  4.     using System.Linq;
  5.  
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             //int[] num = { 9, 2, 5, 8, 1 };
  11.             Console.WriteLine("enter a binary number: ");
  12.             string input = Console.ReadLine();
  13.             //long decimalValue = ToDecimal("101010");
  14.             long decimalValue = ToDecimal(input);
  15.             Console.WriteLine($"Base 10 representation: {decimalValue}");
  16.             int[] nums = decimalValue.ToString().Select(c => int.Parse(c.ToString())).ToArray();
  17.             int sum = Calc(nums, nums.Length - 1);
  18.             bool isDivisibleBy3 = sum % 15 == 0 || sum % 5 == 0 || sum % 3 == 0;
  19.             Console.WriteLine(isDivisibleBy3);
  20.             Console.ReadLine();
  21.         }
  22.  
  23.  
  24.  
  25.         public static long ToDecimal(string binary)
  26.         {
  27.             // 0001
  28.             long value = 0;
  29.  
  30.             int j = 0;
  31.             for (int i = binary.Length - 1; i >= 0; i--)
  32.             {
  33.                 value += (binary[i] == '1' ? 1 : 0) * (int)Math.Pow(2, j++);
  34.             }
  35.             return value;
  36.         }
  37.  
  38.         public static int Calc(int[] numChar, int i)
  39.         {
  40.             if (i < 0)
  41.             {
  42.                 return 0;
  43.             }
  44.             return numChar[i] + Calc(numChar, i - 1);
  45.         }
  46.     }
  47. }
  48.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×