In recreational mathematics, a Niven number in a given number base, is an integer that is divisible by the sum of its digits when written in that base. For example, in base 10, 18 is a Niven number since 18 is divisible by 1+8 = 9. Also, 12001 in base 3 is also a Niven number since the sum of the digits is 4 (which is 11 in base 3) divides 12001 (12001 = 1021 x 11).
Given a base b, any number n < b is trivially a Niven number. We will ignore this case.
Given a base b, and a positive integer T, find the lowest number L such that L, L+1, ..., L+T-1 are all Niven numbers but neither L-1 nor L+T are Niven numbers.
Input Format:
First line contains two integers, b and T
Output Format:
A single integer L such that L, L+1, ..., L+T-1 are all Niven numbers but neither L-1 nor L+T are Niven numbers.
Constraints:
2 ≤ b ≤ 10
1 < T < 7
Example 1
Input
10 4
Output
510
Explanation
510, 511, 512 and 513 are Niven numbers and 514 is not a Niven number. Also 509 is not a Niven number. It can be seen that for N < 510, no four consecutive numbers are Niven numbers.
Example 2
Input
5 5
Output
44
Explanation
44 in base 5 is equivalent to 24 in base 10. Clearly, sum of the digits is 8 = 13 in base 5 and 13 x 3 = 44 in base 5 and hence 44 is a Niven number. Similarly we can see 44+1 = 100, 101, 102 and 103 in base 5 are also Niven numbers. 104 is not a Niven number.
Answers
Answered by
9
import java.util.*;
public class Niven { int t; public static void main(String args[]) {
Niven obj = new Niven(); Scanner sc = new Scanner(System.in); ArrayList<Integer> ls = new ArrayList<>();
System.out.println("Enter integer t"); obj.t = sc.nextInt();
System.out.println("Enter base b"); int base = sc.nextInt(); int x = 11;
while (x < 10000) { int cur = x; for (int i = 0; i < obj.t; i++) { ls.add(cur); cur++;
}
boolean b = obj.check(ls, base);
if (b == true) { System.out.println(toBase(ls.get(0),base)); break; } ls.clear(); x++; } }
public boolean check(ArrayList<Integer> ls, int base) { int count = 0; int sum; int temp1 = 0; for (int temp : ls) { sum = 0;
temp1 = temp; String x = toBase(temp, base); temp = Integer.parseInt(x);
while (temp > 0) {
int var = temp % 10; sum = sum + var; temp = temp / 10;
} if (temp1 % sum == 0) { count++; }
}
if (count == t) { sum = 0; int first = ls.get(0) - 1; int first1 = first; String x2 = toBase(first, base); first = Integer.parseInt(x2);
while (first > 0) { int var1 = first % 10; sum = sum + var1; first = first / 10; } int sum1 = 0; int last = ls.get(ls.size()-1) + 1; int last1 = last; String x3 = toBase(last, base); last = Integer.parseInt(x3); while (last > 0) { int var = last % 10; sum1 = sum1 + var; last = last / 10; } return !((first1 % sum == 0) && (last1 % sum1 == 0)); }
return false;
}
public static String toBase(int n, int base) { if (n == 0) { return "0"; } String binary = ""; while (n > 0) { int rem = n % base; binary = rem + binary; n = n / base; }
return binary; }}
Similar questions