File tree Expand file tree Collapse file tree
10_Harshad_Number/C#/Davipb Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Collections . Generic ;
3+
4+ namespace HarshadNumbers
5+ {
6+ public static class HarshadNumbers
7+ {
8+
9+ /// <summary>
10+ /// Checks weather or not a number is a 10-Harshad Number
11+ /// </summary>
12+ /// <param name="l">The number to be tested</param>
13+ /// <returns>True if l is a Harshad Number</returns>
14+ public static bool IsHarshad ( ulong l )
15+ {
16+ // We don't want division by zero, so let's make sure the universe doesn't explode
17+ if ( l == 0 )
18+ return false ;
19+
20+ ulong sum = 0 ;
21+
22+ // Loop through each digit, adding them to the total sum
23+ foreach ( char c in l . ToString ( ) )
24+ sum += ulong . Parse ( c . ToString ( ) ) ;
25+
26+ // If the remainder of the division is zero, the number is divisble.
27+ return ( l % sum == 0 ) ;
28+ }
29+
30+ // Something extra, the method below is not essential
31+
32+ /// <summary>
33+ /// Generator method that generates all (computable) Harshad Numbers
34+ /// </summary>
35+ /// <returns>Harshad numbers, in crescent order, starting at 1</returns>
36+ public static IEnumerable < ulong > AllHarshadNumbers ( )
37+ {
38+ for ( ulong l = 0 ; ; l ++ )
39+ if ( IsHarshad ( l ) )
40+ yield return l ;
41+ }
42+ }
43+ }
Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Linq ;
4+ using System . Text ;
5+ using System . Threading . Tasks ;
6+
7+ namespace HarshadNumbers
8+ {
9+ public static class HarshadNumbers_test
10+ {
11+ public static void Main ( string [ ] args )
12+ {
13+ Test ( ) ;
14+ Console . ReadKey ( ) ;
15+ }
16+
17+ public static void Test ( )
18+ {
19+ Console . Title = "HarshadNumbers unit test" ;
20+
21+ Console . WriteLine ( "Is N a 10-Harshad number?" ) ;
22+ Console . Write ( "N = " ) ;
23+ Console . WriteLine ( HarshadNumbers . IsHarshad ( ulong . Parse ( Console . ReadLine ( ) ) ) . ToString ( ) ) ;
24+
25+ Console . WriteLine ( ) ;
26+
27+ Console . WriteLine ( "Get the first N 10-Harshad Numbers" ) ;
28+ Console . Write ( "N = " ) ;
29+
30+ int max = int . Parse ( Console . ReadLine ( ) ) ;
31+ for ( int i = 0 ; i < max ; i ++ )
32+ Console . WriteLine ( "{0}: {1}" , i , HarshadNumbers . AllHarshadNumbers ( ) . ElementAt ( i ) ) ;
33+ }
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments