Given an integer N, the task is to check if the concatenation of first N natural numbers is divisible by 3 or not. Print Yes if divisible and No if not.
Input: N = 3
The concatenated number = 123
Since it is divisible by 3, the output is Yes
Input: N = 7
Explanation: The concatenated number = 1234567
Since it is not divisible by 3, the output is No.
The simplest approach is to concatenate the first N natural numbers and calculate the sum of digits of the resultant number and check if it is divisible by 3 or not.
Time Complexity: O(N)
Auxiliary Space: O(1)
To optimize the above approach, we can observe a pattern. The concatenation of first N natural numbers is not divisible by 3 for the following series 1, 4, 7, 10, 13, 16, 19, and so on. The Nth term of the series is given by the formula 3×n +1. Hence, if (N – 1) is not divisible by 3, then the resultant number is divisible by 3, so print Yes. Otherwise, print No.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether factorial of N is divisible by sum of first N natural numbers
- Check if product of first N natural numbers is divisible by their sum
- Check if factorial of N is divisible by the sum of squares of first N natural numbers
- Sum of first N natural numbers which are divisible by X or Y
- Sum of first N natural numbers which are divisible by 2 and 7
- Number of pairs from the first N natural numbers whose sum is divisible by K
- Count natural numbers whose factorials are divisible by x but not y
- Check if the number formed by the last digits of N numbers is divisible by 10 or not
- Find the Nth natural number which is not divisible by A
- Check if a number is formed by Concatenation of 1, 14 or 144 only
- Check if a Sequence is a concatenation of two permutations
- Find the first natural number whose factorial is divisible by x
- Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
- Count of numbers upto M divisible by given Prime Numbers
- Sum of first n natural numbers
- LCM of First n Natural Numbers
- Natural Numbers
- Sum of first N natural numbers which are not powers of K
- Repeated sum of first N natural numbers
- Sum of cubes of even and odd natural numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.