How to resolve the algorithm Harshad or Niven series step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Harshad or Niven series step by step in the Prolog programming language

Table of Contents

Problem Statement

The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order.

The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:

Show your output here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Harshad or Niven series step by step in the Prolog programming language

Source code in the prolog programming language

:- use_module(library(lambda)).

niven :-
	nb_setval(go, 1),

	L = [1 | _],
	print_niven(L, 1),
	gen_niven(1, L).


print_niven([X|T], N) :-
	when(ground(X),
	     (	 (   nb_getval(go, 1)
		 ->  (   N < 20
		     ->  writeln(X),
			 N1 is N+1,
			 print_niven(T, N1)
		     ;	 (   X > 1000
			 ->  writeln(X),
			     nb_setval(go, 0)
			 ;   N1 is N+1,
			     print_niven(T, N1)))
		 ;   true))).



gen_niven(X, [N | T]) :-
	(   nb_getval(go, 1)
	->  X1 is X+1,
	    sum_of_digit(X, S),
	    (   X mod S =:= 0
	    ->  N = X,
		gen_niven(X1, T)
	    ;	gen_niven(X1, [N | T]))
	;   true).


sum_of_digit(N, S) :-
	number_chars(N, LC),
	maplist(\X^Y^number_chars(Y, [X]), LC, LN),
	sum_list(LN, S).


  

You may also check:How to resolve the algorithm Create a file step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Amb step by step in the Perl programming language
You may also check:How to resolve the algorithm Continued fraction step by step in the Quackery programming language
You may also check:How to resolve the algorithm Truncatable primes step by step in the Arturo programming language
You may also check:How to resolve the algorithm System time step by step in the Java programming language