It is a very bad design of the function that does not follow the C++ concepts.
For starters indices in C++ starts from 0. Secondly a range is specified as [start, end)
that is end
is not included in the range.
The function should return an object of the type std::vector<long long>::size_type
. If an element that satisfies the condition is not found in the range then the function should return the value of end
.
I would write the function the following way as it is shown in the demonstrative program
#include <iostream>
#include <vector>
#include <algorithm>
auto solve( const std::vector<long long> &v,
std::vector<long long>::size_type first,
std::vector<long long>::size_type last,
long long value )
{
last = std::min( last, v.size() );
first = std::min( first, last );
auto current = first;
while ( ( current != last ) && ( v[current] % value == 0 ) ) ++current;
return current == first ? last : current - 1;
}
int main()
{
using size_type = std::vector<long long>::size_type;
std::vector<long long> v = { 1, 2, 4, 5, 7, 9 };
size_type first = 1;
size_type last = 3;
long long divisor = 2;
auto i = solve( v, first, last, divisor );
if ( i != last )
{
std::cout << "The last element divisible by " << divisor
<< " in the range [" << first
<< ", " << last
<< ") is at position " << i << '\n';
}
else
{
std::cout << "There is no element divisible by " << divisor
<< " in the range [" << first
<< ", " << last << ")\n";
}
}
Its output is
The last element divisible by 2 in the range [1, 3) is at position 2
You could write the same function using iterators. In this case the function declaration would look simpler.
For example
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
auto solve( std::vector<long long>::const_iterator first,
std::vector<long long>::const_iterator last,
long long value )
{
auto it = std::find_if_not( first, last,
[&value]( const long long &item ) { return item % value != 0; } );
return it == first ? last : std::prev( first );
}
int main()
{
std::vector<long long> v = { 1, 2, 4, 5, 7, 9 };
auto first = std::next( std::cbegin( v ), 1 );
auto last = std::next( std::cbegin( v ), 3 );
long long divisor = 2;
auto it = solve( first, last, divisor );
if ( it != last )
{
std::cout << "The last element divisible by " << divisor
<< " in the range [" << std::distance( std::cbegin( v ), first )
<< ", " << std::distance( std::cbegin( v ), last )
<< ") is at position " << std::distance( std::cbegin( v ), it ) << '\n';
}
else
{
std::cout << "There is no element divisible by " << divisor
<< " in the range [" << std::distance( std::cbegin( v ), first )
<< ", " << std::distance( std::cbegin( v ), last ) << ")\n";
}
}